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.
寻找能够分解为两个三位数乘积的回文数:
先分析,回文数范围在:100^2=10000到999^2=998001之间,暴力也可行……但适当剪枝会快一些
考虑100000及以上时,回文数能被11整除,在循环中就可以抛去其它部分数,解答会快一些。
还想用用时间换空间可以先打个质数表……之类的

1 #include"stdio.h" 2 #include"stdlib.h" 3 #include"string.h" 4 5 int palindrome(int a,int b) /*palindrome function:to test if a product is palindrome*/ 6 { 7 int sum,i,j; 8 char num[8]; 9 sum=a*b; 10 itoa(sum,num,10); 11 for(i=0,j=strlen(num)-1;i<j;i++,j--) 12 if(num[i]!=num[j]) 13 return(0); 14 return(1); 15 } 16 17 int main() /*problem4-Largest palindrome product*/ 18 { 19 int i,j,max=0,m1=0,m2=0; 20 for(i=999;i>=100;i--) 21 for(j=i;j>=100;j--) 22 { 23 if(i%11!=0&&j%11!=0) //剪枝,i,j之中必有一个为11倍数 24 continue; 25 if(palindrome(i,j)==1&&i*j>max) 26 { 27 max=i*j; 28 m1=i; 29 m2=j; 30 } 31 } 32 printf("max palindrome is %d=%d*%d ",max,m1,m2); 33 return(0); 34 }