forked from iiitv/algos
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFibonacciNumber.java
More file actions
32 lines (30 loc) · 893 Bytes
/
FibonacciNumber.java
File metadata and controls
32 lines (30 loc) · 893 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
public class FibonacciNumber {
// fibonacci function return the nth fibonacci no for all n>0
public static int fibonacci(int n) {
if (n == 1 || n == 2) {
return (n - 1);
} else {
// Store second last fibonacci number
int a = 0;
// Store last fibonacci number
int b = 1;
// Store current fibonacci number which is sum of last and second last fibonacci no
int fib = 0;
for (int i = 2; i < n; i++) {
fib = a + b;
a = b;
b = fib;
}
return (fib);
}
}
public static void main(String[] args) {
// n>0
int n = 5;
if (n <= 0) {
System.out.println("n must be greater than 0");
return;
}
System.out.println(fibonacci(n));
}
}