Advertisement
Guest User

Untitled

a guest
Dec 6th, 2015
283
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.05 KB | None | 0 0
  1. import java.util.*;
  2.  
  3.  
  4.  
  5. class fibonacci   {
  6.  
  7.  
  8.  
  9.     public static int fib (int n)  {
  10.  
  11.         int x = 0;
  12.  
  13.        
  14.  
  15.         if (n == 0)
  16.  
  17.             x = 0;
  18.  
  19.         else if (n == 1)
  20.  
  21.             x = 1;
  22.  
  23.         else {
  24.  
  25.             x = fib (n-1) + fib (n-2);
  26.  
  27.         }
  28.  
  29.            
  30.  
  31.         return x;
  32.  
  33.     }
  34.  
  35.    
  36.  
  37.  
  38.  
  39.    public static void main (String args[])     {    
  40.  
  41.  
  42.  
  43.         int num = 0;
  44.  
  45.         int  result = 0;
  46.  
  47.         long start = 0L;
  48.  
  49.         double duration = 0.0;
  50.  
  51.         Scanner stdin = new Scanner(System.in);
  52.  
  53.        
  54.  
  55.         System.out.println("\n--- Java Recursive Ficonacci test ---\n");
  56.  
  57.        
  58.  
  59.         System.out.print("\nEnter initial value: ");
  60.  
  61.        
  62.  
  63.         num = stdin.nextInt();
  64.  
  65.  
  66.  
  67.         // high resolution timer (nanoseconds)
  68.  
  69.         start = System.nanoTime();
  70.  
  71.        
  72.  
  73.         result = fib (num);
  74.  
  75.  
  76.  
  77.         // converting nanoseconds to seconds: nanosecond = 1 billion seconds
  78.  
  79.         duration = ((double) System.nanoTime() - start) / 1000000000.0;
  80.  
  81.  
  82.  
  83.         System.out.println("\n\tFibonacci("+ num +") = "+ result + "\n");
  84.  
  85.        
  86.  
  87.         System.out.printf("\n\t...finished in %4.6f seconds. \n\n", duration);
  88.  
  89.      
  90.  
  91.         System.exit(0);
  92.  
  93.     }
  94.  
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement