Advertisement
ffpaladin

Fib practice

Apr 8th, 2014
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.36 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.Collections;
  3.  
  4.  
  5. public class Fib {
  6.  
  7.     public static void main (String[] args){
  8.        
  9.         System.out.println(fibnum(5));
  10.        
  11.         ArrayList <Integer> fibs = new ArrayList<Integer> ();
  12.        
  13.        
  14.         //The integer passed to the constructor represents its initial capacity,
  15.         //i.e., the number of elements it can hold before it needs to resize its internal array
  16.         //(and has nothing to do with the initial number of elements in the list).
  17.  
  18.         ArrayList<Integer> list = new ArrayList<Integer>(Collections.nCopies(60, 0));
  19.  
  20.        
  21.         for (int i = 0; i < 99; i++){
  22.             if (i < 2) fibs.add(1);
  23.             else fibs.add(fibs.get(i-1) + fibs.get(i-2));
  24.         }
  25.        
  26.         System.out.println(fibs.toString());
  27.        
  28.         // http://introcs.cs.princeton.edu/java/96optimization/Fibonacci.java.html
  29.        
  30.         int N = Integer.parseInt(args[0]);
  31.             if (N < 1 || N > 92) {
  32.                     throw new RuntimeException("N must be between 1 and 92");
  33.             }
  34.  
  35.            long[] fib = new long[N+1];
  36.  
  37.             // base cases
  38.             fib[0] = 0;
  39.             fib[1] = 1;
  40.  
  41.             // bottom-up dynamic programming
  42.             for (int n = 2; n <= N; n++)
  43.                 fib[n] = fib[n-1] + fib[n-2];
  44.  
  45.             // print results
  46.             System.out.println(fib[N]);
  47.  
  48.     }
  49.    
  50.     public static int fibnum (int n){
  51.         if (n<2) return 1;
  52.         else return fibnum (n-1) + fibnum (n-2);
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement