The code is as follows:
Copy the code code as follows:
public class Fibonacci {
public static long recursive(int n) {
if (n <= 0)
return 0;
if(n==1)
return 1;
return recursive(n - 1) + recursive(n - 2);
}
public static long loop(int n) {
if (n <= 0)
return 0;
if(n==1)
return 1;
longfib1 = 0;
longfib2 = 1;
long sum = 0;
for (int i = 2; i <= n; i++) {
sum = fib1 + fib2;
fib1 = fib2;
fib2 = sum;
}
return sum;
}
}
Using recursion is far less efficient than looping!