Problem 4
Largest palindrome product
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
最大回文乘积
回文数就是从前往后和从后往前读都一样的数。由两个2位数相乘得到的最大回文乘积是 9009 = 91 × 99。
找出由两个3位数相乘得到的最大回文乘积。
题目解答
朴素解法:暴力枚举(枚举每一种可能,但是需要考虑交换律的问题,所以如果只想遍历下三角j只需要从i-1开始往下寻找即可)
优化算法: 在本题中求得的是两个三位数乘积的最大回文数,我们通过三位数的边界,我们可以确定这个两个三位数至少可以形成一个5位数,至多可以形成一个6位数。 由于我们所求的是最大的回文数,所以我们只考虑6位的情况即可。
现在我们开始探究6位回文数他所存在的规律:
我们发现所有6位回文数,他一定能够被11整除,借此我们优化我们的程序。
题目代码
#include <stdio.h>
#include <inttypes.h>
#define N 4e6
int32_t judge(int32_t x){
int32_t temp = x;
int32_t new_num = 0;
while (temp != 0){
new_num = new_num * 10 + temp % 10;
temp /= 10;
}
return new_num - x;
}
int32_t main() {
int64_t ans = -0xfffff;
for (int32_t i = 999; i >= 100; i--){
for (int32_t j = i-1; j >= 100; j--){
if(j % 11 != 0) continue;
if (!judge(i * j) && i * j > ans){
ans = i * j;
}
}
}
printf("%" PRId64 "\n",ans);
return 0;
}