▼页尾

[Project Euler] Problem 4

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.

#include <iostream>
using namespace std;

int main(){
int palindrome;
int flag = 0;

for(int i=999; i>100; i--){
palindrome
= 1000*i + i/100 + i%10*100 + i%100/10*10;

for(int j=999; j>100; j--){
if(palindrome%j==0 && palindrome/j <1000){
cout
<< palindrome << endl;
flag
= 1;
break;
}
}

if(flag==1)
break;
}
return 0;
}

六位数的回文数为abccba;

其中 abc 范围为 999~100;

所以六位数的回文数只有900个。

对于每一个回文数,我们看其能不能分解为两个三位数之积

对于最小的六位回文数

100001 / 999 > 100

所以我们只需要

palindrome/j <1000 即可,而不需要 palindrome/j > 100






对于999999,最开始999999/999 = 1001,已经大于1001了,所以对于998~100的数我们不需要最做除法了。

所以简单改进后变为

#include <iostream>
using namespace std;

int main(){
int palindrome;
int flag = 0;

for(int i=999; i>100; i--){
palindrome
= 1000*i + i/100 + i%10*100 + i%100/10*10;

for(int j=999; j>100; j--){
if(palindrome/j > 999)
break;
else if(palindrome%j==0){
cout
<< palindrome << endl;
flag
= 1;
break;
}
}

if(flag==1)
break;
}
return 0;
}
 
posted @ 2011-02-20 22:31  xiatwhu  阅读(322)  评论(0编辑  收藏  举报
▲页首
西