This is supposed to be a super simple program but how many ways can you write it?
Here are a few.
Program 1 – Fibonacci with 2 temp variables
public class Fibonacci {
public static void main(String[] args) {
int n = 10;
int f = 0, g = 1;
for (int i = 1; i <= n; i++) {
f = f + g;
g = f - g;
System.out.println(f);
}
}
}
Program 2 – Fibonacci with 3 temp variables
public class Fibonacci {
public static void main(String args[])
{
int n = 10;
int f1, f2=0, f3=1;
for(int i=1;i<=num;i++)
{
System.out.print(" "+f3+" ");
f1 = f2;
f2 = f3;
f3 = f1 + f2;
}
}
}
Program 3 – Fibonacci using recursion
public class Fibonacci
{
public static void main(String[] args)
{
for(int i=0;i<10;i++)
{
System.out.println(fibonacci(i));
}
}
public static int fibonacci(int n) {
if(n == 0)
return 0;
else if(n == 1)
return 1;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
Program 4 – Fibonacci Using memorization
This method is used to improve the efficiency of our previous algorithms using Memoization. We calculate only the missing values instead of calculating everything everytime.
public class Fibonacci
{
//Cached object to store intermediate results of fibonacci series
private static Map<Integer,Integer> cache = null;
public static void main(String[] args)
{
cache = new HashMap<Integer, Integer>();
for(int i=0;i<10;i++){
System.out.println(fibonacci(i));
}
}
public static int fibonacci(int n) {
//First check if the value is available in the cache. If yes then take it out from there
if(cache.containsKey(n)){
return cache.get(n);
}
int value = 0;
if(n == 0){
value = 0;
}
else if(n == 1){
value = 1;
}
else{
value = fibonacci(n - 1) + fibonacci(n - 2);
}
//Storing the value in cache
cache.put(n, value);
return value;
}
}