patternjavascriptMinor
Even Fibonacci numbers under 4,000,000 (Project Euler #2)
Viewed 0 times
fibonacci000numbersunderprojecteulereven
Problem
Prompt:
Each new term in the Fibonacci sequence is generated by adding the
previous two terms. By starting with 1 and 2, the first 10 terms will
be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not
exceed four million, find the sum of the even-valued terms.
I'd like advice on:
This is my solution:
Each new term in the Fibonacci sequence is generated by adding the
previous two terms. By starting with 1 and 2, the first 10 terms will
be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not
exceed four million, find the sum of the even-valued terms.
I'd like advice on:
- Using mathematical formulas instead of loops to calculate this
- Making the code more efficient
This is my solution:
function EvenFibonacciNumbers(){
var value=parseInt(document.getElementById("input").value);
var sum=0;
var temp=0;
var num2=1;
var num1=1;
while(num2<value){
temp=num1+num2;
num1=num2;
num2=temp;
if(num2%2==0){
sum+=temp;
}
}
//document.getElementById("output").value=sum;
alert("result ="+sum);
}Solution
Naming
var num1
That doesn't tell me what the variable is and does. Is it the smallest Fibonacci number in the two needed to calculate the next?
Operators
Using spaces around your operators helps readability, which helps prevent bugs.
Scope
Algorithm
The Fibonacci numbers go even/odd/odd/even/odd/odd... There is a good reason for this - they start with an even number (0), and an odd number (1). Even numbers plus odd numbers are odd numbers, so we get another odd number (1). Odd numbers plus odd numbers are even numbers, so we know this pattern will continue. With this knowledge, we only need to calculate every 3rd number.
var num1
That doesn't tell me what the variable is and does. Is it the smallest Fibonacci number in the two needed to calculate the next?
Operators
Using spaces around your operators helps readability, which helps prevent bugs.
Scope
temp is only used in the while() loop, so you can reduce its scope.Algorithm
The Fibonacci numbers go even/odd/odd/even/odd/odd... There is a good reason for this - they start with an even number (0), and an odd number (1). Even numbers plus odd numbers are odd numbers, so we get another odd number (1). Odd numbers plus odd numbers are even numbers, so we know this pattern will continue. With this knowledge, we only need to calculate every 3rd number.
Context
StackExchange Code Review Q#94663, answer score: 5
Revisions (0)
No revisions yet.