I am working on a script that will find all the products of any two 3-digit numbers that are palindromes, here are the scripts I'm working on to determine if a number is a palindrome and to compare the products of 3-digit numbers -
var isPalindrome = function(number) {
var number = number.toString();
var length = number.length;
var x = 0;
var y = 1;
while (x<=(length/2)) {
if(number[x]==number[length-y]) {
x++;
y++;
} else {
return false;
}
return true;
}
};
var counter = function() {
var palindromeProducts = [];
var x = i;
var y = 100;
var product = x*y;
while (y<1000) {
for (i=100; i<1000; i++) {
if (isPalindrome(product)) {
palindromeProducts.push(x*y);
}
}
y++;
}
console.log(palindromeProducts);
};
counter();
The isPalindrome function seems to work on palindromes less than 17 digits long, but it will also returns true on some numbers that aren't palindromes and I can't figure out why.
The idea for the palinProduct function is that inside the while loop the for loop will go through all values of x and compare the products, and then the while loop will increase y and then run the for loop again, but it doesn't seem to be working.
In the isPalindrome function, the "return true" statement should be outside the while loop. This was pointed out by Quantastical.
In counter function, there are several problems. i as assigned to x before i is initialized. x is assigned a value once outside of loops and then never changed. product is assigned value once outside of loops and never changed. Code could be simplified by using two for loop that iterate on x and y.
Fixed code might look something like...
var isPalindrome = function(number) {
var number = number.toString();
var length = number.length;
var x = 0;
var y = 1;
while (x<=(length/2)) {
if(number[x]==number[length-y]) {
x++;
y++;
} else {
return false;
}
}
return true;
};
var counter = function() {
var palindromeProducts = [];
for (var x = 100; x < 1000; x++) {
for (var y = 100; y < 1000; y++) {
var product = x*y;
if (isPalindrome(product)) {
palindromeProducts.push(product);
}
}
}
console.log(palindromeProducts);
};