Press "Enter" to skip to content

Posts tagged as “Project Euler”

Project Euler #1 – Multiples of 3 and 5

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

console.log([...Array(1000).keys()]
    .filter(n => n % 3 === 0 || n % 5 === 0)
    .reduce((acc, n) => acc + n));

What is the 10001st prime number?

Javascript Solution:

function getPrimes(max) {
    // create undefined array
    let arr = new Array(max).fill(undefined);
    // fill true for (prime) index i and 
    // fill false for any index that can be multiplied by i
    // prime number start from 2
    for (let i = 2; i < max; i++) {
        if (arr[i] === undefined) arr[i] = true;
        for (let j = i + i; j < max; j += i) {
            arr[j] = false;
        }
    }
    // return index(prime number) and filter out all false
    return arr.map((item, index) => item ? index : false)
              .filter(Boolean);
}

// generate all prime numbers that less than 15000
// the 10001st prime number should lay in that range
let primes = getPrimes(150000); // The number lay in that range
console.log(primes[10000]); // The 10001th prime