Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

Can anyone tell me what's wrong with the code. Find the largest palindrome made from the product of two 3-digit numbers.

function largestPalindrome(){      for(var i =999; i>100; i--){         for(var j = 999; j>100; j--){             var mul = j*i;             if(isPalin(mul)){                 return i * j;             }         }     } }  function isPalin(i){     return i.toString() == i.toString().split("").reverse().join(""); }  console.log(largestPalindrome()); 

This answer was close to my question but still i feel the way i am doing the loop it should return me the largest product.

like image 561
Shane Avatar asked Jan 22 '14 15:01

Shane


People also ask

What is the largest palindrome made from the product of two 3 digit numbers?

The largest palindrome made from the product of two 3-digit numbers is 913 * 993 = 906609. Flowchart: There was a problem connecting to the server.

Should find the largest palindrome made from the product of two 3 digit numbers Javascript?

log(ans); Two loops each range from 100 to 999 for 3-digit number. Then we check the product and record the maximum palindrome. The answer is: 906609.

What is the largest palindrome made from the product of two 2 digit numbers?

The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.

How many 3 digit palindrome numbers are there?

There are 90 palindromic numbers with three digits (Using the Rule of product: 9 choices for the first digit - which determines the third digit as well - multiplied by 10 choices for the second digit): {101, 111, 121, 131, 141, 151, 161, 171, 181, 191, …, 909, 919, 929, 939, 949, 959, 969, 979, 989, 999}


1 Answers

Yours doesn't work properly since it checks 999*999, then 999*998, then 999*997 until it reaches about 999*583. While it doesn't check 997*995 or something closer to the top which generates a larger number

function largestPalindrome(){      var arr = [];         for(var i =999; i>100; i--){         for(var j = 999; j>100; j--){             var mul = j*i;             if(isPalin(mul)){                 arr.push(j * i);             }         }     }      return Math.max.apply(Math, arr); }  function isPalin(i){     return i.toString() == i.toString().split("").reverse().join(""); }  console.log(largestPalindrome()); 

Here is another approach, store all palindrome generated by 3 numbers in an array, then use Math.max on the array to get the largest palindrome

like image 90
Thalaivar Avatar answered Sep 19 '22 13:09

Thalaivar