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

You are watching: 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 questionbut still i feel the way i am doing the loop it should return me the largest product.

javascript
Share
Improve this question
Follow
edited May 23 "17 at 12:34 CommunityBot
asked Jan 22 "14 at 15:21 ShaneShane
2

32
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 topwhich 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

Share
Folshort
answered Jan 22 "14 at 16:01 ThalaivarThalaivar
7
21
I think if you apply maths to the problem you can decrease the guesswork really significantly.

I will write the three digit numbers as 1000 - a and 1000 - b which means the palindrome is 1 000 000 - 1000(a+b) + ab.

First, let"s find solutions where ab . Then the three leftmost digits are 1000 - (a+b) and the three rightmost digits are ab.

See more: What Is The Sugar Found In Rna, What Sugar Is Found In Rna And Dna

Then I will say this is a palindrome with digits x,y,z:

100x+10y+z=ab100z+10y+x=1000-a-bthus

99x-99z = ab+a+b-1000x-z = 1/99(ab+a+b-10)-10So then (ab+a+b-10) is divisible by 99 and we also know that x and z being digits the left side is between -9 and 0 (the whole shebang is symmetrical so we can presume x 1/99(ab+a+b-10) is between 1 and 9. We can rewrite ab+a+b-10 as ab+a+b+1-11=99p so (a+1)(b+1)=99p+11=11*(9p+1) where p runs between 1 and 9. That"s really easy:

for (\$p = 1; \$p Now this prints only one solution which is the correct one.

Now we know 906609 is a solution so then is there a solution where ab > 1000 and 1000(a+b) - ab        