gskll - 8 months ago 36

Javascript Question

I'm looking at projecteuler.net's 4th problem, and have come across a curious feature that I'm wondering if anyone could explain.

The following code returns 10001

`var n = 999 * 999; //biggest product with 3 digit numbers`

var x;

while (n>10000) { //smallest product of 3 digit numbers

if (n.toString() === n.toString().split('').reverse().join('')) {

x = Math.floor(Math.sqrt(n));

while (n % x !== 0 && x >= 100 && n/x <= 999) {

x--;

}

if (n % x === 0 && x>= 100 && n/x <= 999) {

n;

}

}

n--;

}

whereas when wrapped in an IIFE, it returns 906609 which is the correct answer.

`(function euler4() {`

var n = 999 * 999; //biggest product with 3 digit numbers

var x;

while (n>10000) { //smallest product of 3 digit numbers

if (n.toString() === n.toString().split('').reverse().join('')) {

x = Math.floor(Math.sqrt(n));

while (n % x !== 0 && x >= 100 && n/x <= 999) {

x--;

}

if (n % x === 0 && x>= 100 && n/x <= 999) {

return n;

}

}

n--;

}

}());

Does anybody know why? I can't find an explanation online. Cheers!

Answer Source

The lone `n`

in the first does not terminate the algorithm, whereas the `return n`

in the second does. This can be fixed by replacing `n`

in the first with a simple `break`

```
var n = 999 * 999; //biggest product with 3 digit numbers
var x;
while (n>10000) { //smallest product of 3 digit numbers
if (n.toString() === n.toString().split('').reverse().join('')) {
x = Math.floor(Math.sqrt(n));
while (n % x !== 0 && x >= 100 && n/x <= 999) {
x--;
}
if (n % x === 0 && x>= 100 && n/x <= 999) {
break;
}
}
n--;
}
console.log(n);
```