public class FibanocciSeries {
public static void main(String[] args) {
// 0 1 1 2 3 5 8 13.....
// 0 1 2 3 4 5 6 7.....
int n = getNthFibanocciNumber_Rec(4);
System.out.println(n);// recursively calculated value
n = fib(4);
System.out.println(n);// fibanocci number without recursion
}
public static int fib(int n) {
int a = 0, b = 1, c = 1;
while (n > 1) {
c = a + b;
a = b;
b = c;
n--;
}
return c;
}
public static int getNthFibanocciNumber_Rec(int n) {
if (n == 0)
return 0;
if (n == 1 || n == 2)
return 1;
else
return getNthFibanocciNumber_Rec(n - 1)
+ getNthFibanocciNumber_Rec(n - 2);
}
}
Refer this for O(logN) solution :
http://tech-queries.blogspot.com/2010/09/nth-fibbonacci-number-in-ologn.html
Checking given number is fibanocci or not: A positive integer ω is a Fibonacci number if and only if one of 5ω2 + 4 and 5ω2 - 4 is a perfect square.
bool isFibonacci(int w)
{
double X1 = 5 * Math.Pow(w, 2) + 4;
double X2 = 5 * Math.Pow(w, 2) - 4;
long X1_sqrt = (long)Math.Sqrt(X1);
long X2_sqrt = (long)Math.Sqrt(X2);
return (X1_sqrt*X1_sqrt == X1) || (X2_sqrt*X2_sqrt == X2) ;
}
Finding Nth Fibonacci number using Dynamic Programming :
static int[] fib = new int[10];
//Top down approach(memorization)
static int getFibanocci(int n) {
if(n<=1){
fib[n]=n;
}
else if(fib[n]==0){
fib[n] = getFibanocci(n-1)+getFibanocci(n-2);
}
return fib[n];
}
//bottom up approach(tabulation)
static int getFibanocciNumber_BottomUp(int n){
int[] a = new int[n+1];
a[1]=1;
for(int i=2;i<=n;i++){
a[i] = a[i-1]+a[i-2];
}
return a[n];
}
No comments:
Post a Comment