File tree Expand file tree Collapse file tree 1 file changed +18
-25
lines changed Expand file tree Collapse file tree 1 file changed +18
-25
lines changed Original file line number Diff line number Diff line change 1
- #include < iostream>
2
-
3
-
4
- int main ()// main fibonacci program
5
- {
6
- int fib1 = 0 ;
7
- int fib2 = 1 ;
8
- int fib3 = 0 ;
9
- int c;
10
- int sum=0 ;
11
- // decalare all variables
12
- std::cout << " How many fibonacci numbers do you want to sum?" << std::endl;
13
- std::cin >> c;
14
- // get user input and print the first "0" and "1"
15
- std::cout << fib1 << std::endl;;
16
- std::cout << fib2 << std::endl;
17
- for (int i = 0 ; i < c; i++)// Looping though the fibonacci algorithm
18
- {
19
- fib3 = fib1 + fib2;
20
- sum += fib3;
21
- fib1 = fib2;
22
- fib2 = fib3;
23
- }
24
- std::cout<<sum<<endl;
25
- 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 less tahn n
13
+ size--;
14
+ } // now decraese the largest fibonaici number from n
15
+ n=n-fib[size];
16
+ ans++;
17
+ }
18
+ return ans;
26
19
}
You can’t perform that action at this time.
0 commit comments