I'm having trouble with my code. It stops working at this line:
if (value1 < 4000000 && value.isInteger(value1/2))
Here's my function:
function fibonacciSum() {
let value1 = 1;
let value2 = 2;
let total = 0;
while (value1 && value2 < 4000000) {
if (value1 < 4000000 && value.isInteger(value1/2)) {
total += value1;
}
if (value2 < 4000000 && value.isInteger(value2/2)) {
total += value2;
}
value1 = value1 + value2;
value2 = value1 + value2;
}
alert(total);
}
fibonacciSum();
Can anyone spot the issue? The program doesn’t run past the first if statement inside the while loop. I’m trying to sum up even Fibonacci numbers below 4 million. Thanks for any help!
I’ve encountered similar issues before, and I think I see the problem in your code. The main issue is with the value.isInteger()
method. In JavaScript, isInteger()
is a method of the Number
object, not value
. You should use Number.isInteger()
instead.
Also, your while loop condition isn’t quite right. You’re checking if both values are less than 4 million, but you only need one to be. Here’s how I’d modify your function:
function fibonacciSum() {
let value1 = 1;
let value2 = 2;
let total = 0;
while (value1 < 4000000) {
if (value1 % 2 === 0) {
total += value1;
}
let temp = value1 + value2;
value1 = value2;
value2 = temp;
}
alert(total);
}
This should work correctly. I’ve simplified the even number check to value1 % 2 === 0
, which is more efficient. Hope this helps!
hey mate, i think i kno whats goin on. ur using value.isInteger()
which aint a thing in js. try Number.isInteger()
or just do value1 % 2 === 0
to check for even nums. also ur while loop looks funky. mayb try while (value1 < 4000000)
instead. hope that helps!
I see the issue in your code. The problem lies in the value.isInteger()
method. JavaScript doesn’t have this method on regular numbers. Instead, you should use Number.isInteger()
or a simpler approach like checking if the remainder is zero when divided by 2.
Here’s a corrected version of your function:
function fibonacciSum() {
let value1 = 1;
let value2 = 2;
let total = 0;
while (value1 < 4000000) {
if (value1 % 2 === 0) {
total += value1;
}
let temp = value1 + value2;
value1 = value2;
value2 = temp;
}
alert(total);
}
This should work as intended. The while loop condition has been simplified, and the even number check is now more straightforward. Give it a try and let us know if you have any other questions.