Created
July 10, 2017 15:23
-
-
Save satveersm/09b750311775d471d2fc5afa43ed4a60 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
How many minimum numbers from fibonacci series are required such that sum of numbers should be equal to a given Number N? | |
Note : repetition of number is allowed. | |
Example: | |
N = 4 | |
Fibonacci numbers : 1 1 2 3 5 .... so on | |
here 2 + 2 = 4 | |
so minimum numbers will be 2 | |
--------------------------------------------------------------------------------------------------------------------------- | |
int Solution::fibsum(int A) { | |
//Generate all fib no upto A | |
std::set<int> s; | |
int a = 1; | |
int b = 1; | |
s.insert(1); | |
while(b <= A) | |
{ | |
int c = a + b; | |
a = b; | |
b = c; | |
s.insert(c); | |
} | |
int count = 0; | |
std::set<int>::reverse_iterator itr = s.rbegin(); | |
while(itr != s.rend()) | |
{ | |
if(*itr == A) | |
{ | |
count++; | |
break; | |
} | |
else if(A > *itr) | |
{ | |
count++; | |
A = A - *itr; | |
} | |
else | |
{ | |
itr++; | |
} | |
} | |
return count; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment