Skip to content

Commit f5af9d3

Browse files
author
Sahil
authored
Merge pull request royalpranjal#20 from CodeLogist/patch-1
Merging Sum of Fibonacci Numbers.
2 parents 51aac34 + 5aaa117 commit f5af9d3

File tree

1 file changed

+18
-38
lines changed

1 file changed

+18
-38
lines changed

Graphs/SumOfFibonacciNumbers.cpp

Lines changed: 18 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,19 @@
1-
// https://www.interviewbit.com/problems/sum-of-fibonacci-numbers/
2-
3-
int Solution::fibsum(int A) {
4-
// Do not write main() function.
5-
// Do not read input, instead use the arguments to the function.
6-
// Do not print the output, instead return values as specified
7-
// Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details
8-
9-
vector<int> vec;
10-
11-
vec.push_back(1);
12-
vec.push_back(1);
13-
14-
int fib, i = 2;
15-
16-
while(fib <= A){
17-
fib = vec[i-2] + vec[i-1];
18-
vec.push_back(fib);
19-
i++;
20-
}
21-
22-
int j = vec.size()-1;
23-
int sol = 0;
24-
25-
LOOP:while(A && j >= 0){
26-
if(vec[j] == A){
27-
sol++;
28-
return sol;
29-
}
30-
else if(vec[j] < A){
31-
sol++;
32-
A = A - vec[j];
33-
goto LOOP;
34-
}
35-
j--;
36-
}
37-
38-
return 0;
1+
int Solution::fibsum(int n) {
2+
vector <int> fib;
3+
fib.push_back(1);fib.push_back(1); // now u have 1 and 1 at v[0] and v[1]
4+
for(int i=2;fib[i-1]<n;i++){
5+
int val=fib[i-1]+fib[i-2];
6+
fib.push_back(val);
7+
}
8+
int ans=0;
9+
int size=fib.size();
10+
size--;
11+
while(n>0){
12+
while(fib[size]>n){ // find the largest fibonaci number < n
13+
size--;
14+
} // now decraese the largest fibonaci number from n
15+
n=n-fib[size];
16+
ans++;
17+
}
18+
return ans;
3919
}

0 commit comments

Comments
 (0)