代码之家  ›  专栏  ›  技术社区  ›  Rania Saeed

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

  •  2
  • Rania Saeed  · 技术社区  · 7 年前

    我试图计算特定范围内的斐波那契数(以千为单位的大范围数字)

    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;    
        }   
      }
    }
    
    4 回复  |  直到 7 年前
        1
  •  2
  •   Mohamed Benmahdjoub    7 年前
     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;
     }
    
        2
  •  0
  •   C4rbyn3m4n    7 年前

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

    while(n3<8386589){
     if(n3>5027){
        System.out.print(n3+" ");    
     }
     n3=n1+n2;    
     n1=n2;    
     n2=n3; 
    }
    
        3
  •  0
  •   EJoshuaS - Stand with Ukraine    7 年前

    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);
                }
            }
        }
    
        4
  •  0
  •   Korteby Farouk    7 年前

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