【欧拉计划4】Largest palindrome product

时间:2023-03-08 21:51:26

欢迎访问我的新博客:http://www.milkcu.com/blog/

原文地址:http://www.milkcu.com/blog/archives/1371281760.html

原创:【欧拉计划4】Largest palindrome product

摘要:找出两个3位数乘积得到的最大回文数

作者:MilkCu

题目描述

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.

我的解答

第一次做的答案是580085,提交后提示错误,原来程序逻辑错误,得出的并不是最大的。增加max判断后,程序就对了。

# include <stdio.h>

int isPal(int n);
int reverse(int n); int main(void)
{
int p;
int max = 0;
for(int i = 999; i >= 100; i--) {
for(int j = 999; j >= i; j--) {
p = i * j;
if(isPal(p)) {
if(p > max) {
max = p;
} else {
break;
}
}
}
}
printf("%d\n", max);
} int isPal(int n)
{
if(n == reverse(n)) {
return 1;
} else {
return 0;
}
} int reverse(int n)
{
int r = 0;
do {
r = r * 10 + n % 10;
} while(n /= 10);
return r;
}

不断改进

看了projecteuler.net给的pdf,内容大致如下:

  1. 变量j的循环从i开始;
  2. 变量i和j的循环由大到小;
  3. 回文数必被11整除;

从第三点得到的启发还是很大的。

我们可以从下面的关系式得出这个结论:

P = 100000x + 10000y + 1000z + 100z + 10y + x

P = 100001x + 10010y + 1100z

P = 11 * (9091x + 910y + 100z)

改进后的代码如下:

# include <stdio.h>

int isPal(int n);
int reverse(int n); int main(void)
{
int p;
int max = 0;
int i, j, step;
for(i = 999; i >= 100; i--) {
if(i % 11 == 0) {
j = 999;
step = 1;
} else {
j = 990;
step = 11;
}
for(; j >= i; j--) {
p = i * j;
if(isPal(p)) {
if(p > max) {
max = p;
} else {
break;
}
}
}
}
printf("%d\n", max);
} int isPal(int n)
{
if(n == reverse(n)) {
return 1;
} else {
return 0;
}
} int reverse(int n)
{
int r = 0;
do {
r = r * 10 + n % 10;
} while(n /= 10);
return r;
}

最后答案

906609

(全文完)