Project Euler Problem #30

in code


Problem #30 was solved on new ground: my first run through Project Euler was in rigid order of first to last ending at #25. The recent round of solutions mostly cover old ground, which works well for me by itself because it shows off how my code has improved since 2012.

Cookie in a basket

Also, the run of text post has led to a sharp reduction in cute cat photographs, so here’s one of Cookie in a basket.

Problem #30 has two components:

  1. Find the upper bounds for the problem.
  2. Find the sum of appropriate numbers.

So, uh, to paraphrase, possible values for the problem fall into a range with a top end somewhere roundabouts n * 9n, where n is the power you want to raise all the digits:

5 * 9^5 = 354294

After that it is simple and easy to test numbers in the range:

function probableMax(power) {
    return power * Math.pow(9, power);
}

function powerDigits(number, power) {
    return (number).toString().split('').map(digit => {
        return Math.pow(parseInt(digit), power);
    }).reduce((sum, current) => {
        return sum + current;
    });
}

const power = 5;
let sum = 0;

for (let i = 2; i < probableMax(power); i++) {
    if (powerDigits(i, power) === i) {
        sum += i;
    }
}

console.log(sum);


Coffee is Good

in code


Your email address will not be published. Required fields are marked *