Sum all Odd Fibonacci Numbers

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.