回文数的两种读法都一样。两个两位数的乘积构成的最大回文数是9009 = 91 × 99。
找出由两个 3 位数的乘积组成的最大回文。
我写了这段代码来寻找解决方案,但 Project Euler 网站上的答案仍然不正确:
function Palindromic(x) {
var pal = parseInt(x.toString().split('').reverse().join(''));
if (pal === x)
return true;
else
return false;
}
var x = 100,
y = 100,
product = x * y;
for (x; x <= 999; x++) {
for (y = x; y <= 999; y++) {
product = x * y;
if (Palindromic(product)) {
console.log(x + '*' + y + '=' + product);
}
}
}
我的代码有问题吗?! 不管怎样,我得到的答案是 888888 来自 924*962
最佳答案
我不认为,您的代码存在真正的问题。你只是不过滤最大的产品,这不一定是你最后的输出。只需为最大的产品添加额外的支票,例如像这样:
var x, y, product, max = 0;
for (x = 100; x <= 999; x++) {
for (y = x; y <= 999; y++) {
product = x * y;
if (Palindromic(product)) {
if( max < product ) { // this is new
max = product;
console.log(x + '*' + y + '=' + product);
}
}
}
}
返回
913*993=906609
作为最大的结果。
关于javascript - Javascript 中最大的回文积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18842861/