public class FibonacciCalculator {
public static void main(String[] args) {
int number = 12;
System.out.println("Fibonacci series upto " + number + " numbers : "); //printing Fibonacci series upto number
for (int i = 1; i <= number; i++) {
System.out.print(fibonacci2(i) + " ");
}
}
public static int fibonacci2(int number) {
if (number == 1 || number == 2) {
return 1;
}
int fibo1 = 1, fibo2 = 1, fibonacci = 1;
for (int i = 3; i <= number; i++) { //Fibonacci number is sum of previous two Fibonacci number
fibonacci = fibo1 + fibo2;
fibo1 = fibo2;
fibo2 = fibonacci;
}
return fibonacci;
}
public static int fibonacci(int number) {
if (number == 1 || number == 2) {
return 1;
}
return fibonacci(number - 1) + fibonacci(number - 2); //tail recursion
}
public static int getFibonacci(int n) {
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
}
int first = 0;
int second = 1;
int nth = 1;
for (int i = 2; i <= n; i++) {
nth = first + second;
first = second;
second = nth;
}
return nth;
}
}
Comments
Post a Comment