Advertisement
brilliant_moves

BigFibonacci.java

Feb 21st, 2016
281
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.29 KB | None | 0 0
  1. import java.util.Scanner;
  2. import java.math.BigInteger;
  3. import java.text.DecimalFormat;
  4.  
  5. public class BigFibonacci {
  6.  
  7.     /**
  8.     *   Program:    BigFibonacci.java
  9.     *   Creator:    Chris Clarke
  10.     *   Created:    06.10.2013
  11.     *   Purpose:    Calculate the first n terms in Fibonacci series.
  12.     *   Notes:      Uses BigInteger class.
  13.     */
  14.  
  15.     private static final int        MAX = 270;
  16.     private static BigInteger[]     Fib = new BigInteger[MAX+1];
  17.  
  18.     public static void printFibonacciSeries(int n) {
  19.         DecimalFormat df = new DecimalFormat(",###");
  20.         for (int i=1; i<=n; i++) {
  21.             switch(i) {
  22.                 case 1 : case 2 :
  23.                     Fib[i] = new BigInteger("1"); break;
  24.                 default:
  25.                     Fib[i] = Fib[i-2].add(Fib[i-1]);
  26.             }//end switch
  27.             System.out.println( i+": " + df.format( Fib[i]));
  28.         }//end for
  29.     }//end printFibonacci()
  30.  
  31.     public static void main(String[] args) {
  32.         Scanner keybd = new Scanner(System.in);
  33.         int n=0;
  34.  
  35.         System.out.print("\nEnter number between 1 and "+MAX+": ");
  36.  
  37.         do {
  38.             n = keybd.nextInt();
  39.             if (n<1 || n>MAX) {
  40.                 System.out.println("Number outside range [1.."+MAX+"].  Try again: ");
  41.             }//end if
  42.         } while (n<1 || n>MAX);
  43.  
  44.         System.out.println("\nThe first "+n+" numbers in the Fibonacci series are:");
  45.  
  46.         // print the first n Fibonacci numbers
  47.         printFibonacciSeries(n);
  48.     }//end main()
  49. }//end class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement