Tell us what’s happening:
I looked for the hint and I don’t understand the code given there to find the prime numbers. Please help me understand the code…
I don’t understand the code form line 11
Your code so far
function sumPrimes(num) {
var res = 0;
// Function to get the primes up to max in an array
function getPrimes(max) {
var sieve = [];
var i;
var j;
var primes = [];
for (i = 2; i <= max; ++i) {
if (!sieve[i]) {
// i has not been marked -- it is prime
primes.push(i);
for (j = i << 1; j <= max; j += i) {
sieve[j] = true;
}
}
}
return primes;
}
// Add the primes
var primes = getPrimes(num);
for (var p = 0; p < primes.length; p++) {
res += primes[p];
}
return res;
}
// test here
sumPrimes(10);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:83.0) Gecko/20100101 Firefox/83.0.
No. The number is stored as binary. <<1 shifts everything in the binary representation one to the left, which is the same as multiplying by two. If I recall correctly the Wikipedia article on bitwise operations is pretty good.
The code uses a bitshift to start j at i*2 and then sets every multiple of j that’s less than or equal to max as ‘true’, which I’m assuming means not prime.