Java Program for n-th Fibonacci numbers
Last Updated :
24 Jul, 2023
In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation
Fn = Fn-1 + Fn-2
with seed values
F0 = 0 and F1 = 1.
Method 1 ( Use recursion )
Java
class Fibonacci {
static int fib( int n)
{
if (n== 0 )
return 0 ;
else if (n== 1 || n== 2 )
return 1 ;
return fib(n - 1 ) + fib(n - 2 );
}
public static void main(String args[])
{
int n = 9 ;
System.out.println(fib(n));
}
}
|
Method 2 ( Use Dynamic Programming )
Java
class Fibonacci {
static int fib( int n)
{
int f[] = new int [n + 1 ];
int i;
f[ 0 ] = 0 ;
if (n > 0 ) {
f[ 1 ] = 1 ;
for (i = 2 ; i <= n; i++) {
f[i] = f[i - 1 ] + f[i - 2 ];
}
}
return f[n];
}
public static void main(String args[])
{
int n = 9 ;
System.out.println(fib(n));
}
}
|
Method 3 ( Use Dynamic Programming with Space Optimization)
Java
class Fibonacci {
static int fib( int n)
{
int a = 0 , b = 1 , c;
if (n == 0 )
return a;
for ( int i = 2 ; i <= n; i++) {
c = a + b;
a = b;
b = c;
}
return b;
}
public static void main(String args[])
{
int n = 9 ;
System.out.println(fib(n));
}
}
|
Method 4 (Divide and Conquer)
Java
class Fibonacci {
static int fib( int n)
{
int F[][] = new int [][] { { 1 , 1 }, { 1 , 0 } };
if (n == 0 )
return 0 ;
power(F, n - 1 );
return F[ 0 ][ 0 ];
}
static void multiply( int F[][], int M[][])
{
int x = F[ 0 ][ 0 ] * M[ 0 ][ 0 ] + F[ 0 ][ 1 ] * M[ 1 ][ 0 ];
int y = F[ 0 ][ 0 ] * M[ 0 ][ 1 ] + F[ 0 ][ 1 ] * M[ 1 ][ 1 ];
int z = F[ 1 ][ 0 ] * M[ 0 ][ 0 ] + F[ 1 ][ 1 ] * M[ 1 ][ 0 ];
int w = F[ 1 ][ 0 ] * M[ 0 ][ 1 ] + F[ 1 ][ 1 ] * M[ 1 ][ 1 ];
F[ 0 ][ 0 ] = x;
F[ 0 ][ 1 ] = y;
F[ 1 ][ 0 ] = z;
F[ 1 ][ 1 ] = w;
}
static void power( int F[][], int n)
{
int i;
int M[][] = new int [][] { { 1 , 1 }, { 1 , 0 } };
for (i = 2 ; i <= n; i++)
multiply(F, M);
}
public static void main(String args[])
{
int n = 9 ;
System.out.println(fib(n));
}
}
|
Method 5 (Divide and Conquer)
Java
class Fibonacci {
static int fib( int n)
{
int F[][] = new int [][] { { 1 , 1 }, { 1 , 0 } };
if (n == 0 )
return 0 ;
power(F, n - 1 );
return F[ 0 ][ 0 ];
}
static void multiply( int F[][], int M[][])
{
int x = F[ 0 ][ 0 ] * M[ 0 ][ 0 ] + F[ 0 ][ 1 ] * M[ 1 ][ 0 ];
int y = F[ 0 ][ 0 ] * M[ 0 ][ 1 ] + F[ 0 ][ 1 ] * M[ 1 ][ 1 ];
int z = F[ 1 ][ 0 ] * M[ 0 ][ 0 ] + F[ 1 ][ 1 ] * M[ 1 ][ 0 ];
int w = F[ 1 ][ 0 ] * M[ 0 ][ 1 ] + F[ 1 ][ 1 ] * M[ 1 ][ 1 ];
F[ 0 ][ 0 ] = x;
F[ 0 ][ 1 ] = y;
F[ 1 ][ 0 ] = z;
F[ 1 ][ 1 ] = w;
}
static void power( int F[][], int n)
{
if (n == 0 || n == 1 )
return ;
int M[][] = new int [][] { { 1 , 1 }, { 1 , 0 } };
power(F, n / 2 );
multiply(F, F);
if (n % 2 != 0 )
multiply(F, M);
}
public static void main(String args[])
{
int n = 9 ;
System.out.println(fib(n));
}
}
|
Please refer complete article on Program for Fibonacci numbers for more details!
Share your thoughts in the comments
Please Login to comment...