-
Notifications
You must be signed in to change notification settings - Fork 0
/
N th Fibonacci Number
79 lines (56 loc) · 1.65 KB
/
N th Fibonacci Number
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
Problem statement
The n-th term of Fibonacci series F(n), where F(n) is a function, is calculated using the following formula -
F(n) = F(n - 1) + F(n - 2),
Where, F(1) = 1, F(2) = 1
Provided 'n' you have to find out the n-th Fibonacci Number. Handle edges cases like when 'n' = 1 or 'n' = 2 by using conditionals like if else and return what's expected.
"Indexing is start from 1"
Example :
Input: 6
Output: 8
Explanation: The number is ‘6’ so we have to find the “6th” Fibonacci number.
So by using the given formula of the Fibonacci series, we get the series:
[ 1, 1, 2, 3, 5, 8, 13, 21]
So the “6th” element is “8” hence we get the output.
Detailed explanation ( Input/output format, Notes, Images )
Sample Input 1:
6
Sample Output 1:
8
Explanation of sample input 1 :
The number is ‘6’ so we have to find the “6th” Fibonacci number.
So by using the given formula of the Fibonacci series, we get the series:
[ 1, 1, 2, 3, 5, 8, 13, 21]
So the “6th” element is “8” hence we get the output.
Expected time complexity :
The expected time complexity is O(n).
Constraints:
1 <= 'n' <= 10000
Where ‘n’ represents the number for which we have to find its equivalent Fibonacci number.
Time Limit: 1 second
Solution :
//Java
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner a=new Scanner(System.in);
int n=a.nextInt();
System.out.println(F(n));
}
int count=0;
static int F(int n){
int count=0;
int ini=1;
int tot=0;
for(int i=1;i<=n;i++){
if(n==1||n==2){
count++;
}
else{
tot=ini+count;
ini=count;
count=tot;
}
}
return tot;
}
}