/home/wpollock1/public_html/Java/Fibonacci.java
// Calculate the n-th Fibonacci number, using a recursive
// method. (This value can be calculated using a non-recursive
// algorithm more more efficiently, but I want to demonstrate
// recursion with a simple example.)
// Note Java long will overflow after 92nd Fibonacci number,
// but the inefficiency means it will take hours/days to compute
// (roughly) the 60th Fibonacci number! For a faster recursive algorithm,
// see FibonacciMemo.java. The fastest way is to avoid recursion; see
// the iterative algorithm below. To avoid the overflow, use BigInteger
// objects instead of a long.
//
// Usage: Pass in the number as a command line argument.
//
// Written 11/2016 by Wayne Pollock, Tampa Florida USA
class Fibonacci
{
private static long count = 0; // count of the calls to the method fib
public static void main ( String [] args )
{
int num = 0;
try {
num = Integer.parseInt( args[0] );
if ( num < 0 )
throw new IllegalArgumentException( "Must be a positive Integer" );
} catch ( Exception e ) {
System.err.println( "Usage: java Fibonacci <num>\n"
+ "\twhere <num> is a positive Integer" );
System.exit( 1 );
}
System.out.println( "fib(" + num + ") = "
+ fib( num ) );
System.out.println( "\nNumber of calls to method fib: " + count );
}
private static long fib ( int num )
{
++count; // Count how many times this method is invoked
// fib(0) and fib(1) are 0 and 1 by definition:
if ( num == 0 ) return 0;
if ( num == 1 ) return 1;
// fib(n) is fib(n-1) + fib(n-2) by definition:
return fib( num-1 ) + fib( num-2 );
}
}
/* Iterative version:
public static void main ( String [] args )
{
// Test values: Note the overflow that occurs for large values.
int[] values = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 50, 92, 93, -1};
for ( int val : values )
System.out.println( "fib(" + val + ") = " + fib(val) );
}
private static long fib ( int num )
{
if ( num < 0 )
throw new IllegalArgumentException("num must be non-negative!");
if ( num == 0 ) return 0;
if ( num == 1 ) return 1;
// Initialize first two values:
long previous = 0, current = 1, next;
// Calculate fib(num):
for ( int i = 2; i <= num; ++i ) {
next = previous + current;
previous = current;
current = next;
}
return current;
}
*/