Created
June 14, 2014 15:16
-
-
Save bencoveney/ed2feaec35e12349415a to your computer and use it in GitHub Desktop.
Largest Palindrome Product
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var limit = 1000; | |
var highestPalindrome = 0; | |
var isPalindrome = function(number) | |
{ | |
// Split the number into an array of digits | |
// To do this we need to make javascript think the number is a string of text | |
// the string of text can then be split into individual characters | |
var numberString = "" + number; | |
var digits = numberString.split(""); | |
// reverse the array | |
var digitsReversed = []; | |
for(var i = 0; i < digits.length; i++) | |
{ | |
digitsReversed[digits.length - (i + 1)] = digits[i]; | |
} | |
// Check if the arrays are equal | |
// we do this by comparing length and then comparing every element | |
// the number is assumed to be a palindrome until it is found to not be one | |
var isItAPalindrome = true; | |
if(digits.length === digitsReversed.length) | |
{ | |
for(var i = 0; i < digits.length; i++) | |
{ | |
if(digits[i] != digitsReversed[i]) | |
{ | |
isItAPalindrome = false; | |
} | |
} | |
} | |
else | |
{ | |
// Different lengths (wat) | |
isItAPalindrome = false; | |
} | |
return isItAPalindrome; | |
} | |
// Loop through every 2 number combination | |
for(var i = 0; i < limit; i++) | |
{ | |
for(var j = i; j < limit; j++) | |
{ | |
// Multiply them | |
var product = i * j; | |
// If the result is a palindrome (and higher than the current highest) record it | |
if(isPalindrome(product) && product > highestPalindrome) | |
{ | |
highestPalindrome = product; | |
console.log(highestPalindrome + " is the new highest palindrome"); | |
} | |
} | |
} | |
isPalindrome(999); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment