2017-07-28 44 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;  
}