-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFig10_40.java
More file actions
39 lines (36 loc) · 864 Bytes
/
Copy pathFig10_40.java
File metadata and controls
39 lines (36 loc) · 864 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public class Fig10_40
{
/**
* Compute Fibonacci numbers as described in Chapter 1.
*/
public static int fib( int n )
{
if( n <= 1 )
return 1;
else
return fib( n - 1 ) + fib( n - 2 );
}
/**
* Compute Fibonacci numbers as described in Chapter 1.
*/
public static int fibonacci( int n )
{
if( n <= 1 )
return 1;
int last = 1;
int nextToLast = 1;
int answer = 1;
for( int i = 2; i <= n; i++ )
{
answer = last + nextToLast;
nextToLast = last;
last = answer;
}
return answer;
}
public static void main( String [ ] args )
{
System.out.println( "fib( 7 ) = " + fib( 7 ) );
System.out.println( "fibonacci( 7 ) = " + fibonacci( 7 ) );
}
}