-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNthFibonacciTerm.java
40 lines (35 loc) · 1.06 KB
/
NthFibonacciTerm.java
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
40
package math;
public class NthFibonacciTerm {
/**
* Main method of the class for the following question:
* Find the nth term of the Fibonacci series.
* </br>
* The sequence typically begins like this:
* 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...
*/
public static void main(String[] args) {
java.util.Scanner scanner = new java.util.Scanner(System.in);
System.out.print("Enter number: ");
int number = scanner.nextInt();
System.out.println("The " + number + " term of the Fibonacci series: " + nthFibonacciTerm(number));
}
private static int nthFibonacciTerm(int number) {
if (number <= 0) {
return 0;
} else if (number == 1) {
return 1;
} else if (number == 2) {
return 1;
} else {
int a = 0;
int b = 1;
int c = 1;
for (int i = 3; i <= number; i++) {
c = a + b;
a = b;
b = c;
}
return c;
}
}
}