java - Show the arithmetic of Fibonacci numbers? -
import static java.lang.system.*; class na_false { public static void main(string[] args) { int fibonacci = fibo(5); system.out.println(fibonacci); } static int fibo(int n) { if (n == 0 || n == 1) { out.println(n); return n; } else { int n1 = fibo(n - 1); int n2 = fibo(n - 2); out.println((n1 + n2) + "=" + n1 + "+" + n2); return n1 + n2; } } } i want show how each fibonacci number many unnecessary steps.
using recursion pretty simple -
public static int fibo(int n){ if(n == 1 || n == 2){ return 1; } return fibo(n-1) + fibo(n -2); } now main method can call print -
int fibonacci = fibo(5); system.out.println(fibonacci); update: when want step step result may use following solution using loop -
public class fibotest{ public static void main(string[] args){ int term = fibo(17); //1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 system.out.println(); system.out.println("result: " +term); } public static int fibo(int n){ int first = 1; int second = 1; int third = 0; for(int i=1; i<(n-1); i++){ third = first+second; system.out.println(first +" + "+ second +" = "+ third); //update first , second terms first = second; second = third; } return third; } }
Comments
Post a Comment