Help! Problem 30: Digit n powers

Tell us what’s happening:
The code can not pass the last test.
I think the prevention of infinite loop is causing this.
How can I change my code to pass the tests.

Your code so far


function digitnPowers(n) {
  var numbers = [];
  var start = 2;
  var added = 0;
  while(true){
    var Str = start.toString();
    for(let i = 0; i<Str.length; i++){
      added += Math.pow(Number(Str[i]),n) 
    }
    if(added == start){
      numbers.push(added);
    }
    added = 0;
    start++;
  }

  return console.log(numbers);
}

digitnPowers(5);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/coding-interview-prep/project-euler/problem-30-digit-n-powers/

Hey,

Looks like your while loop will be running forever, right?

nope. Now freecodecamp can not allow infinite loop,
so there is a limit in the while loop. If I change the condition of while loop to limit the “start” value. The result is the same. And the limitation of iteration by freecodecamp seems causing my problem.
So, I am thinking another way to do more efficient iteration.

There’s got to be some kinda bug.

I don’t see any way to check such a huge range of numbers without using iteration.

Heres my attempt. I figured the most efficient way would just be to set the limit to 500000.

1 Like