Skip to content

Commit 253de8a

Browse files
author
jsquared21
committedOct 2, 2015
Add Ex 18.2
1 parent db3369e commit 253de8a

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed
 
1.13 KB
Binary file not shown.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/*********************************************************************************
2+
* (Fibonacci numbers) Rewrite the fib method in Listing 18.2 using iterations. *
3+
* Hint: To compute fib(n) without recursion, you need to obtain fib(n - 2) and *
4+
* fib(n - 1) first. Let f0 and f1 denote the two previous Fibonacci numbers. The *
5+
* current Fibonacci number would then be f0 + f1. The algorithm can be *
6+
* described as follows: *
7+
* *
8+
* f0 = 0; // For fib(0) *
9+
* f1 = 1; // For fib(1) *
10+
* *
11+
* for (int i = 1; i <= n; i++) { *
12+
* currentFib = f0 + f1; *
13+
* f0 = f1; *
14+
* f1 = currentFib; *
15+
* } *
16+
* // After the loop, currentFib is fib(n) *
17+
* *
18+
* Write a test program that prompts the user to enter an index and displays its *
19+
* Fibonacci number. *
20+
*********************************************************************************/
21+
import java.util.Scanner;
22+
23+
public class Exercise_18_02 {
24+
/** Main method */
25+
public static void main(String[] args) {
26+
// Create a Scanner
27+
Scanner input = new Scanner(System.in);
28+
29+
// Prompt the user to enter an index
30+
System.out.print("Enter an index for a Fibonacci number: ");
31+
int index = input.nextInt();
32+
33+
// Find and display the Fibonacci number
34+
System.out.println("The Fibonacci number at index "
35+
+ index + " is " + fib(index));
36+
37+
}
38+
39+
/** The method for finding the Fibonacci number */
40+
public static long fib(long index) {
41+
long f0 = 0; // For fib(0)
42+
long f1 = 1; // For fib(1)
43+
long currentFib = 0;
44+
45+
if (index == 0)
46+
return f0;
47+
else if (index == 1)
48+
return f1;
49+
else {
50+
for (int i = 1; i < index; i++) {
51+
currentFib = f0 + f1;
52+
f0 = f1;
53+
f1 = currentFib;
54+
}
55+
return currentFib;
56+
}
57+
}
58+
}

0 commit comments

Comments
 (0)
Please sign in to comment.