Get to know the strange JavaScript Array.indexOf phenomenon (in Node.js)
When I try to solve ProjectEuler No.27 I came across a weird JavaScript Array.indexOf problem (in Node.js), The code looks like this:
var primes = require('./primes1000.js');
var bigPrimes = require('./primes50000.js');
var maxNumber = 2;
var maxPair = {};
var getQuadratic = function(b) {
var i = 0;
var a = 0;
while (Math.abs(a) < 1000) {
var prime = primes[i];
var a = prime - 1 - b;
var length = getMaxNumber(a, b) - 1;
if (length > maxNumber) {
maxNumber = length;
maxPair = {
a: a,
b: b
};
console.log(maxPair, maxNumber);
}
i++;
}
};
var getMaxNumber = function(a, b) {
var isPrime = true;
var n = 1;
while (isPrime) {
n = n + 1;
var result = (n + a) * n + b;
isPrime = (bigPrimes.indexOf(result) !== -1);
// if ((a === 1) & (b === 41)) {
// console.log(result, isPrime);
// }
}
return n;
};
for (var i = 0; i < primes.length; i++) {
getQuadratic(primes[i]);
}
primes1000.js and primes50000.js are written like this:
module.exports = [2,3,5,7,11,13,17,...,997];
module.exports = [2,3,5,7,11,13,17,...,611953];
The problem arises when
bigPrimes.indexOf(result)
When the result is 47, the indexOf method returns -1, which means it was not found.
After a lot of debugging and testing, finally I changed node to
bigPrimes.indexOf(parseInt(result))
Then it works.
But the result
typeof result
and
typeof bigPrimes[14]
- both "numbers" AND
parseInt(result) === result
returns true.
I didn't understand why I need parseInt to get the correct indexOf return value.
+3
source to share