2017-07-28 42 views
2

我想要計算特定範圍內的斐波納契數字(數以千計的數字範圍很寬) 我已經寫了這個但我不知道要修改它以使其例如,我需要5027和8386589如何獲得範圍內斐波那契數列沒有遞歸

class Fibonacci 
{ 
    public static void main(String args[]) 
    {  
    int n1=0,n2=1,n3,i,count=10;  
    System.out.print(n1+" "+n2);//printing 0 and 1  

    for(i=2;i<count;++i)  
    {  
     n3=n1+n2;  
     System.out.print(" "+n3);  
     n1=n2;  
     n2=n3;  
    } 
    } 
} 
+1

5027和8386589是不是一個斐波那契數,所以你想要的範圍在2個給定的正常數字之間,是嗎? – hamena314

+0

如果你想在一系列值之間執行斐波那契並且想避免從1開始......你至少需要序列的前兩個值,否則你將無法得到下一個值。 – araknoid

+0

你想擺脫它什麼?只需在給定範圍內打印數字?或者獲取範圍內的數字列表?或者數它們?或者是什麼? – Ray

回答

2
int fib(int low, int high){ 
     // Initialize first three Fibonacci Numbers 
     int n1 = 0, n2 = 1, n3 = 1; 

     // Count fibonacci numbers in given range 
     int result = 0; 

     while (n1 <= high){ 
      if (n1 >= low) 
       result++; 
      f1 = f2; 
      f2 = f3; 
      f3 = f1 + f2; 
     } 

     return result; 
} 
+0

這個計數的斐波納契數該範圍內的數字; OP想要什麼? 「我需要得到斐波納契數字在5027和8386589之間」有點不清楚。 – Ray

+0

至少這就是我所理解的:')@Ray。 – Calips

+0

感謝你的幫助我這麼多 –

0

之間得到斐波那契數的範圍內嘗試使用while循環,而不是一個for循環,包括if語句

while(n3<8386589){ 
if(n3>5027){ 
    System.out.print(n3+" ");  
} 
n3=n1+n2;  
n1=n2;  
n2=n3; 
} 
+0

現在使它並行/並行;-) – user499211

+0

這工作正常與我,謝謝 –

0

FWIW,這裏是我的版本(也使用while環路):

private static void Fibonacci(long lower, long upper) 
    { 
     long curr = 1, prev = 1; 

     while (curr <= upper) 
     { 
      long temp = curr; 

      curr = prev + curr; 

      prev = temp; 

      if (curr >= lower && curr <= upper) 
      { 
       System.out.println(curr); 
      } 
     } 
    } 
+0

非常感謝你的努力我明白現在清楚 –

0

的一些想法只是使用的BigInteger更大的價值:

private static BigInteger function_f(int n) { 

    // if n = 0 => f(n) = 0 
    if(n == 0) 
     return new BigInteger("0"); 

    // Initialization of variables 
    // if n = 1 => f(n) = 1 (case included) 
    BigInteger result = new BigInteger("1"); 
    BigInteger last_fn = new BigInteger("0"); 
    BigInteger before_last_fn = new BigInteger("0"); 

    // Do the loop for n > 1 
    for (int i = 2; i <= n; i++) { 

     // f(n - 2) 
     before_last_fn = last_fn; 
     // f(n - 1) 
     last_fn = result; 
     // f(n - 1) + f(n - 2) 
     result = last_fn.add(before_last_fn); 

    } 

    // Return the result 
    return result;  
}