如何在不递归的情况下获得范围内的斐波那契数列

how to get fibonacci series within range without recursion

我正在尝试计算特定范围内的斐波那契数(范围广泛,以千为单位) 我已经写了这个但是因为我不知道要修改它以使其在一个范围内例如我需要获得 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;    
    }   
  }
}
 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;
 }

尝试使用 while 循环而不是 for 循环并包含 if 语句

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

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);
            }
        }
    }

一些想法只是使用 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;      
}