DEV Community

Discussion on: Project Euler Problem 4 Solved with Javascript

Collapse
 
dhurak profile image
Dhurak

A few possible optimizations:

  • Inner loop only has to iterate from i to 0 instead of largestNum to 0
  • We can break out of inner loop whenever product drops below highest

With both optimizations we go from almost 600k palindrome tests to about 6k tests with largestNum equal to 999.

Collapse
 
codenutt profile image
Jared

Hi Dhurak! I think I'm confused by what you mean. In your scenario, what is the i value?

Collapse
 
dhurak profile image
Dhurak • Edited

for (let j = largestNum; j > 0; j--)

can become:

for (let j = i; j > 0; j--)

The inner loop does not have to start from the very beginning every time.
First set would be 99x99, 99x98, 99x97... 99x1
Second set would be 98x98, 98x97, 98x96... 98x1
Third set: 97x97, 97x96, 97x95... 97x1

In second set you don't test 98x99 because you already tested 99x98 in first set.

Thread Thread
 
codenutt profile image
Jared

Ohhh, I see. That's genius. Thank you!