如何在Java中檢查一個數是否為Keith數?


如果一個數可以由其數字組成的特殊序列排列,則稱該數為Keith數。

之後,序列中的數字將透過將之前的數字相加來生成,直到數字超過輸入數字。如果最終數字與輸入數字相同,則結果將被確定。

在生成序列期間新增之前的數字時,請記住只新增第n個數字,其中n指的是原始輸入數字中的位數。

在本文中,我們將學習如何使用Java程式語言檢查一個數是否為Keith數。

舉幾個例子

例1

輸入數字是19

讓我們使用Keith數的邏輯來檢查它:

透過分離19的數字,我們得到第一個序列= 1, 9。

現在將所有數字相加:1 + 9 = 10。

現在新的序列是1, 9, 10。

現在將最後兩個數字相加:9 + 10 = 19。

所以新的序列是1, 9, 10, 19。

在這裡我們可以看到序列的最後一個數字與我們的輸入數字或原始數字相同。

因此,19是一個Keith數。

例2

輸入數字是197

讓我們使用Keith數的邏輯來檢查它:

透過分離197的數字,我們得到第一個序列= 1, 9, 7。

現在將所有數字相加:1 + 9 + 7 = 17。

現在新的序列是1, 9, 7, 17。

現在將最後三個數字相加:9 + 7 + 17 = 33。

新的序列是1, 9, 7, 17, 33。

現在將最後三個數字相加:7 + 17 + 33 = 57。

新的序列是1, 9, 7, 17, 33, 57

如果我們遵循相同的步驟,我們將得到序列= 1, 9, 7, 17, 33, 57, 107, 197。

在這裡我們可以看到序列的最後一個數字與我們的輸入數字或原始數字相同。

因此,197是一個Keith數。

例3

輸入數字是152

讓我們使用Keith數的邏輯來檢查它:

透過分離152的數字,我們得到第一個序列= 1, 5, 2。

現在將所有數字相加:1 + 5 + 2 = 8。

現在新的序列是1, 5, 2, 8。

現在將最後三個數字相加:5 + 2 + 8 = 15。

新的序列是1, 5, 2, 8, 15。

現在將最後三個數字相加:2 + 8 + 15 = 25。

新的序列是1, 5, 2, 8, 15, 25。

如果我們遵循相同的步驟,我們將得到序列= 1, 5, 2, 8, 15, 25, 48, 88, 161。

在這裡我們可以看到序列的最後一個數字超過了我們的輸入數字或原始數字。

因此,152不是一個Keith數。

其他一些Keith數的例子包括19、197、742、1537等。

演算法

  • 步驟1 - 獲取一個整數,可以透過初始化或使用者輸入獲得。

  • 步驟2 - 宣告一個數組來儲存計算出的數字。

  • 步驟3 - 首先找到輸入數字的位數。

  • 步驟4 - 然後,使用我們在迴圈內的演算法,計算下一個值,直到值超過輸入數字。

  • 步驟5 - 最後,我們將比較最後一個計算出的數字與輸入數字,如果兩者相同,我們將得出結論:輸入數字是Keith數;否則,輸入數字不是Keith數。

方法

我們提供了不同的方法來解決這個問題。

  • 使用靜態輸入值

讓我們逐一檢視程式及其輸出。

方法:使用靜態輸入值

在這種方法中,將要求使用者輸入輸入數字,然後使用該演算法檢查該數字是否為Keith數。

示例

public class Main{ //main method public static void main(String[] args){ //declared an integer variable and initialized the value int inputNumber = 14; //print the given input number System.out.println("Given number: "+inputNumber); //store it to an another temporary variable int temporaryNumber = inputNumber; //type casting it to string String str = Integer.toString(inputNumber); //find the length and store the length value into a variable int len =str.length(); //declare a array which store the input number int store[]=new int[inputNumber]; int i, sum; //initiate the looping for break the input number into single digits for(i=len-1; i>=0; i--){ // store the digits into the same array store[i]=temporaryNumber % 10; temporaryNumber = temporaryNumber/10; } i=len; sum=0; //start iteration for calculating the next numbers while(sum<inputNumber){ sum = 0; for(int j=1; j<=len; j++){ sum=sum+store[i-j]; } //store the calculated numbers into the array store[i]=sum; i++; } //check the resultant number is matched to the input number or not if(sum==inputNumber) System.out.println(inputNumber + " is a Keith Number."); else System.out.println(inputNumber + " is not a Keith Number."); } }

輸出

Given number: 14
14 is a Keith Number.

在本文中,我們探討了如何使用不同的方法在Java中檢查一個數是否為Keith數。

更新於:2022年10月27日

2K+ 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.