Advertisement
Guest User

fibonacciIterRecur

a guest
Jan 22nd, 2020
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.35 KB | None | 0 0
  1. public class Main {
  2.  
  3.     public static int fibonacciSequence(int n0, int n1, int elements){
  4.         if(n0 == n1) System.out.print(String.format(" %d %d", n0,n1));
  5.  
  6.         if(elements == 0){
  7.             return n0 + n1;
  8.         }
  9.         int currentValue = n0 + n1;
  10.         System.out.print(String.format(" %d", currentValue));
  11.  
  12.         return(fibonacciSequence(n1,currentValue,elements-1));
  13.     }
  14.  
  15.     public static void main(String[] args) {
  16.  
  17.         int n0 = 1;
  18.         int n1 = 1;
  19.         int elements;
  20.  
  21.         System.out.print("\nPlease provide how many of Fibonacci series should I list: ");
  22.         Scanner scanner = new Scanner(System.in);
  23.  
  24.         if(scanner.hasNextInt()){
  25.             elements = scanner.nextInt();
  26.             System.out.println(String.format("Will resolve Fibonacci series for %d elements",elements));
  27.  
  28.             System.out.println("Iteration:");
  29.             System.out.print(String.format("%d %d", n0,n1));
  30.             for (int i = 0; i < elements; i++) {
  31.                 int nextN = n0+n1;
  32.                 System.out.print(String.format(" %d",nextN));
  33.  
  34.                 n0 = n1;
  35.                 n1 = nextN;
  36.             }
  37.  
  38.             System.out.println("\nRecursion");
  39.             fibonacciSequence(1,1,elements);
  40.         } else {
  41.             System.out.println("Provided input wasn't an int!");
  42.         }
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement