-1

I'm currently trying to find a solution for the Project Euler Problem 4 in Codecamp. This solution is working with 2 digits, but for 3 is gives instead of the correct result 90909 as answer. As I'm still new to JS I'm not able to find the problem. Thx in advance!

  function largestPalindromeProduct(digit) {
  var result;
  var a;
  var b;
  if(digit == 2){
     a = 99;
     b = 99;
  }else{
     a = 999;
     b = 999;
  }
  for(var i = 1; i <= a; i++){
    for(var y = 1; y <= b ; y++){
      var calc = i*y;
      var calcString = calc.toString();
      var calcStringReverse = calcString.split('').reverse().join('');
      if(calcString == calcStringReverse){
        result = calc;
      }
      }
    }
  return result;
}


largestPalindromeProduct(3);
AtJack
  • 1
  • 1

1 Answers1

0

In your solution you loop over all values and update the result variable if a palindrome is found, BUT you never check whether the new palindrome is larger than the currently selected one, which results in the last found palindrome always being returned (90909).

Here's the corrected code:

function largestPalindromeProduct(digit) {
    // We'll initialize "result" with a value, as we'll be using it later on
    var result = 0;
    var a;
    var b;
    if (digit == 2) {
        a = 99;
        b = 99;
    } else {
        a = 999;
        b = 999;
    }

    for (var i = 1; i <= a; i++) {
        for (var y = 1; y <= b ; y++) {
            var calc = i * y;
            var calcString = calc.toString();
            var calcStringReverse = calcString.split('').reverse().join('');
            // This is the fundamental change necessary to get it working as intended
            if (calcString === calcStringReverse && calc > result) {
                result = calc;
            }
        }
    }
    return result;
}

If you want to further improve your code, I'd suggest reversing your loops and returning the first palindrome encountered, which would improve the method's speed.

Chris Satchell
  • 751
  • 5
  • 17