Advertisement
brilliant_moves

Fibonacci.java

Oct 1st, 2012
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 0.80 KB | None | 0 0
  1. import java.util.Scanner;   // for user input
  2.  
  3. public class Fibonacci {
  4.  
  5.     public static void main(String[] args) {
  6.         Scanner scan = new Scanner(System.in);
  7.         int n;
  8.  
  9.         System.out.println("I will compute the Nth term in the Fibonacci Series.");
  10.  
  11.         do {
  12.             System.out.print("Please enter a value for N: ");
  13.             n = scan.nextInt();
  14.             if (n>40) System.out.println("Number too big! Must be 40 or less");
  15.             if (n<1) System.out.println("Number too small! Must be 1 or more");
  16.         } while (n>40 || n<1);
  17.  
  18.         System.out.println((int) fib(n));
  19.     }
  20.  
  21.     public static double fib(int n) {
  22.         for (int i=1; i<=n; i++) {
  23.             switch(i) {
  24.                 case 1 :    F[i] = 1; break;
  25.                 case 2 :    F[i] = 1; break;
  26.                 default  :  F[i] = F[i-2] + F[i-1];
  27.             }
  28.         }
  29.         return F[n];
  30.     }
  31.  
  32.     private static double[] F = new double[101];
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement