When I first saw Fibonacci, I just wrote the algorithm for calculating the Fibonacci sequence. And then I found out the pit, and I thought it was interesting to share it.
Topic
Returns all the odd sums in the Fibonacci sequence that are less than the passed-in value, and if the incoming value is a Fibonacci number, it should also participate in the summation.
The first few numbers in the Fibonacci sequence are 1, 1, 2, 3, 5, and 8, and each subsequent number is the sum of the first two digits.
For example, passing 4 to a function should return 5, because all the odd numbers less than 4 in the Fibonacci sequence are 1, 1, 3.
Test:
Sumfibs (1) should return a number.
Sumfibs (1000) should return 1785.
Sumfibs (4000000) should return 4613732.
Sumfibs (4) should return 5.
Sumfibs (75024) should return 60696.
Sumfibs (75025) should return 135721.
Ideas
After a closer look at the requirements, it was found that only the odd numbers in the Fibonacci sequence were required. I was so full of people, this pit dad and asked me how much the university disposable money almost ... Not many words, since understand the need to start.
Let's first list the meaning of the Fibonacci number: F (n) =f (n-1) +f (n-2) +...+f (1), we just need to extract the odd and add in the Fibonacci sequence that is smaller than the value passed in.
Declares a sum variable, inserting a trinocular operator in the calculation of the Fibonacci sequence algorithm to determine if the current value in the sequence is an odd number, and if it is added to the sum variable.
Do not die in words to start writing code:
1 functionsumfibs (num) {2 varA=0,b=0,c=1,sum=0;3 for(vari=0;c<=num;i++){4sum+= (c%2==1?c:0);5A=b;6b=C;7c=a+b;8 }9 returnsum;Ten}
Explain the above ... Never mind. In addition to a pit quite simple algorithm, do not parse has not understood can message asked me, look forward to chatting with you clam clam
Sum all Odd Fibonacci Numbers