user6732041
user6732041

Reputation:

My Solution to the Largest Palindrome of the product of two 3 digit numbers needs work

The answer I'm getting is not the correct one (correct answer is 906609). Please help me understand where I am going wrong. I want the while loop to go from 100 to 999 while multiplying itself against the current i value before the loop increments it.

// A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.

// Find the largest palindrome made from the product of two 3-digit numbers.

var pali = [];

function palindrome() {
for (var i = 100; i <= 999; i++) {
    var counter = 100;
    
    while (counter <= 999) {
      var result = counter * i;
      if (result.toString() === result.toString().split("").reverse().join("")) {
        pali.push(result);
      }   
      counter++;
    }
}
  return pali[pali.length - 1];
}

console.log(palindrome());

Upvotes: 1

Views: 271

Answers (3)

The Rookie Coder
The Rookie Coder

Reputation: 124

I think the easiest way will be to add a If statement.

function palindrome() 
    {
        var max = 0;
        for (var i = 999; i >= 100; i--) 
        {
            var counter = 999;
            while (counter >= 100) 
            {
                var result = counter * i;
                if (result.toString() === result.toString().split("").reverse().join("")) 
                {
                    if(result>max)
                    {
                         max = result;
                    }
                }   
                counter++;
            }
        }
        return max;
     }

Upvotes: -1

Jared
Jared

Reputation: 964

Lengthier, but faster. Starting at the max values and working down, short circuiting when we won't find higher values:

function largestPalindromeProduct(lower, upper) {
  var palindrome = 0;
  var outerLow = lower;
  var outer = upper;
  while (outer > outerLow) {
    var inner = upper;
    var innerLow = lower;
    while (inner > innerLow) {
      var result = inner * outer;
      if (result + "" === (result + "").split("").reverse().join("")) {
        if (result > palindrome) {
          palindrome = result;
          outerLow = inner; // Don't go lower than this value in the outer, no need!
        }
        inner = innerLow; // short-circuit this loop
      }
      inner--;
    }
    outer--;
  }
  return palindrome;
}

console.log(largestPalindromeProduct(100, 999))

Upvotes: 0

Jeremy Jackson
Jeremy Jackson

Reputation: 2257

You're going to have to sort the array in ascending order if you want the last one to be the highest:

pali.sort(function(a, b){return a-b});

Using that, I get 906609.

Upvotes: 2

Related Questions