-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIterativeFibonacciAtIndex.java
More file actions
27 lines (23 loc) · 947 Bytes
/
Copy pathIterativeFibonacciAtIndex.java
File metadata and controls
27 lines (23 loc) · 947 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
// Christopher Yonek
// Compute Fibonacci (Iteration)
import java.util.Scanner;
public class IterativeFibonacciAtIndex {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an index for the Fibonacci number: ");
int index = input.nextInt();
long startTime = System.nanoTime();
System.out.println("Fibonacci number at index " + index + " is " + fibonacciLoop(index));
long elapsedTime = System.nanoTime() - startTime;
System.out.println(elapsedTime);
}
public static int fibonacciLoop(int numAtEnd) { //use loop
int secondPrevNum, prevNumber = 0, numberGiven = 1;
for (int i = 1; i < numAtEnd ; i++) {
secondPrevNum = prevNumber;
prevNumber = numberGiven;
numberGiven = secondPrevNum + prevNumber;
}
return numberGiven;
}
}