Advertisement
zoltanvi

Fibonacci number calculator (recursive + iterative)

Jul 16th, 2018
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.15 KB | None | 0 0
  1.  
  2. public class Main {
  3.  
  4.     public static void main(String[] args) {
  5.  
  6.         for (int i = 0; i < 20; i++) {
  7.             System.out.println(fibR(i));
  8.         }
  9.  
  10.         System.out.println("=============");
  11.  
  12.         for (int i = 0; i < 20; i++) {
  13.             System.out.println(fibI(i));
  14.         }
  15.  
  16.     }
  17.  
  18.     // Recursive fibonacci calculator
  19.     public static int fibR(int n) {
  20.         if (n < 0) {
  21.             throw new IllegalArgumentException();
  22.         } else if (n == 0) {
  23.             return 0;
  24.         } else if (n == 1) {
  25.             return 1;
  26.         } else {
  27.             return fibR(n - 1) + fibR(n - 2);
  28.         }
  29.     }
  30.  
  31.     // Iterative fibonacci calculator
  32.     public static int fibI(int n){
  33.         if(n < 0){
  34.             throw new IllegalArgumentException();
  35.         } else if(n == 0){
  36.             return 0;
  37.         } else if(n == 1){
  38.             return 1;
  39.         } else {
  40.             int a = 0;
  41.             int b = 1;
  42.             int c = 0;
  43.  
  44.             for (int i = 1; i < n; i++) {
  45.                 c = a + b;
  46.                 a = b;
  47.                 b = c;
  48.             }
  49.             return c;
  50.         }
  51.     }
  52.  
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement