Source of FibonacciIterative.java


  1: //FibonacciIterative.java
  2: 
  3: public class FibonacciIterative
  4: {
  5:     public static void main(String[] args)
  6:     {
  7:         long n = Long.parseLong(args[0]);
  8:         long i;
  9:         for (i = 1; i <= n; i++)
 10:         {
 11:             System.out.printf("%19d", fibIterative(i));
 12:             if (i % 4 == 0)
 13:             {
 14:                 System.out.println();
 15:             }
 16:         }
 17:         if ((i - 1) % 4 != 0)
 18:         {
 19:             System.out.println();
 20:         }
 21:     }
 22: 
 23:     //Computes and returns the nth Fibonacci number,
 24:     //using an iterative algorithm
 25:     private static long fibIterative(long n)
 26:     {
 27:         if (n <= 2)
 28:         {
 29:             return 1;
 30:         }
 31:         else
 32:         {
 33:             long secondLast = 1;
 34:             long last = 1;
 35:             for (int i = 1; i <= n - 2; ++i)
 36:             {
 37:                 long sumOfLastTwo = last + secondLast;
 38:                 secondLast = last;
 39:                 last = sumOfLastTwo;
 40:             }
 41:             return last;
 42:         }
 43:     }
 44: }