[英]I want to Copy the Largest number from one file to another File?But, I cannot find the largest Number
[英]I want to subtract the largest possible number from the Fibonacci sequence by decreasing it in
我想從用戶那里得到n
並通過按順序減少它從斐波那契數列中減去最大可能的數字並繼續這個過程直到它達到零。 我們的斐波那契數列從 1 開始。數字 88 可以是 1 + 3 + 8 + 21 + 55 的形式寫到這些數字分別是斐波那契數列的句子 1、3、5、7 和 9。
輸入: 88
輸出: 9 7 5 3 1
我的代碼:
class Main {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int[] fibo = new int[1000];
int[] arr = new int [100];
int d = 0;
int b = 0;
fibo[1] = 1;
fibo[2] = 2;
for (int i = 3, j = 1; i <= 20; i++, j++)
fibo[i] = fibo[i - 1] + fibo[i - 2];
b = n;
for (int i = 1, j = 1; i <= 20 && b >= 0; i++, j++) {
if (b == fibo[i] || b + 1 == fibo[i] || b - 1 == fibo[i]) {
d = i;
b -= fibo[d - 1];
System.out.println("B= " + b);
arr[j] = d - 1;
System.out.println("arr= " + arr[j]);
}
}
}
}
第一個問題是,每次從數字中減去某個值時,您將減去的下一個數字必須更小 - 因為您的數字本身現在更小 - 而在您的代碼中,數字只會越來越大。
例如,在您嘗試第 9 個斐波那契數 55 之后,您正在嘗試 89,而您應該嘗試 34。
這可以通過向后迭代斐波那契數來解決,就像從數組末尾的最大數字開始一樣,這樣隨着循環的迭代,數字變小。
第二個問題是你在 if 語句中的檢查,只有當恰好有一個與你所在的數字非常接近的斐波納契數時才會滿足。
相反,如果您想選擇小於您的數字的最大斐波那契數,您可以只檢查“小於您的數字”部分,因為“最大斐波納契”部分已經由 for 循環的工作方式處理.
這是工作代碼。 您還會注意到變數少了很多。 此外,我對輸入編號進行了硬編碼以進行測試,您必須重新添加掃描儀的內容。抱歉。
public class Main {
public static int len = 20; // the program considers this many fibonacci numbers
public static void main(String args[])
{
int n = 88;
int[] fibo = new int[len];
for(int i=0; i<len; i++)
{
if (i < 2) fibo[i] = i+1; // for 1 and 2
else fibo[i] = fibo[i-1] + fibo[i-2]; // for 3 and 5 and ...
}
for(int i=len-1; i>=0; i--)
{
if (fibo[i] <= n)
{
System.out.format("%d: %d - %d = %d\n",
i+1, // to correct for 0-indexing
n, fibo[i], n-fibo[i]);
n -= fibo[i];
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.