Advertisement
brilliant_moves

QuickFibonacciRecursiveSeries.java

Jan 7th, 2015
465
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.20 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class QuickFibonacciRecursiveSeries {
  4.  
  5.     /**
  6.     *   Program:    QuickFibonacciRecursiveSeries.java
  7.     *   Purpose:    Calculate the first n terms in the Fibonacci series
  8.     *   Creator:    Chris Clarke
  9.     *   Created:    06/10/2013
  10.     */
  11.  
  12.     private static final int MAX = 92;
  13.  
  14.     public static long fib(int n) {
  15.         return fiboHelp(0, 1, n);
  16.     } // fibRecursive()
  17.  
  18.     public static long fiboHelp(long x, long y, int n) {
  19.         // recursive function
  20.         if (n == 0)
  21.             return x;
  22.         else if (n == 1)
  23.             return y;
  24.         else
  25.             return fiboHelp(y, x+y, n-1);
  26.     } // fiboHelp()
  27.  
  28.     public static void main(String[] args) {
  29.         Scanner keybd = new Scanner(System.in);
  30.         int n = 0;
  31.         long f = 0;
  32.  
  33.         System.out.print("Enter number between 1 and "+MAX+": ");
  34.         do {
  35.             n = keybd.nextInt();
  36.             if (n<1 || n>MAX) {
  37.                 System.out.print("Number outside range [1.."+MAX+"].  Try again: ");
  38.             } // if
  39.         } while (n<1 || n>MAX);
  40.  
  41.         System.out.println("\nThe first "+n+" numbers in the Fibonacci series are:");
  42.  
  43.         // print first n Fibonacci numbers
  44.         for (int i=1; i<=n; i++) {
  45.             f = fib(i);
  46.             if (f<0) break;
  47.             System.out.println(i+": " + f);
  48.         } // end for
  49.     } // main()
  50.  
  51. } // class QuickFibonacciRecursiveSeries
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement