DEV Community

Discussion on: Project Euler #4 - Largest Palindrome Product

Collapse
 
silvestricodes profile image
Jonathan Silvestri

A quadratic solution in JavaScript. I'm curious if there's a way to do this in linear time:

const array = new Array(900).fill(0).map((e, i) => i + 100);

const isPalindrome = num => {
  return (
    String(num) ===
    String(num)
      .split("")
      .reverse()
      .join("")
  );
};

const maxProduct = range => {
  let palindrome = 0;
  for (let i = 0; i < range.length; i++) {
    for (let j = i + 1; j < range.length; j++) {
      const product = array[i] * array[j];
      if (isPalindrome(product) && product > palindrome) {
        palindrome = product;
      }
    }
  }

  return palindrome;
};

console.log(maxProduct(array));
Collapse
 
maxart2501 profile image
Massimo Artizzu • Edited

Not linear... but I think (without any actual proof 🤷‍♂️) (I'm a fraud 🤦‍♂️) that my solution does it in logarithmic time: dev.to/maxart2501/comment/b9m6

Edit: scratch that, no way it's not quadratic 😂 But then again, it's faster than the extensive check.