[Project Euler] 来做欧拉项目练习题吧: 题目004
?? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??[Project Euler] 來做歐拉項目練習題吧: 題目004
?? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 周銀輝
?
?
問題描述:
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.?
(先思考,如果有興趣先編程試試,然后才看下面的內容)???
?
?
問題分析:
求兩個三位數相乘能都得到的最大回文數(回文:從前到后閱讀和從后向前閱讀都一樣)?
很簡單的思路:a: 100~999 ?b: 100~999 ,然后對每個a*b進行判斷其是否是回文數,然后在找出最大的。
先看如何判斷一個數(比如9119)是否是回文數。
你可以利用itoa和strrev將其轉換成字符串,然后調用字符串反轉函數,最后看反轉后的字符串和原字符串是否相等,但我更建議下面的方法:
int is_palindromic(int n){int reverse ? = 0;int quotient ?= n;int remainder = 0;while(quotient > 0){remainder = quotient%10;quotient ?= quotient/10;reverse ? = reverse*10 + remainder;}//test//printf("reversed:%d\n", reverse);return n==reverse;}?
然后是挨個去試乘積是否是回文數,并找出最大的:
int a, b, c, max=0;
for(a=100; a<=999; a++)
{
for(b=100; b<=999; b++)
{
c = a*b;
if(is_palindromic(c) && c>max)
{
max = c;?
}?
}?
}?
但注意到,上面的兩個for循環是可以優化的:
由于,題目要求的是最大的回文數而不是求所有的,所以for循環應該從999向100遞減,這樣當發現當前的c值小于上一次計算出來的回文數時,就可以停止循環了,因為接下來的值會更小:
int a, b, c, max=0;
for(a=999; a>=100; a--)
{
for(b=999; b>=100; b--)
{
c = a*b;
if(c<max)
{
break;
}?
if(is_palindromic(c))
{
max = c;?
}?
}?
}?
再來,由于乘法具有交換律,所以a=x, b=y 和 a=y, b=x所得乘積是一樣的,那么上面的兩層循環存在重復運算,最簡單的例子是a=1,b=999時和a=999, b=1時,所以代碼可以寫成:
int Test(){int i, j, product;int max = 0;int best_i, best_j, times=0;//just for testfor(i=999; i>100; i--){for(j=999; j>=i; j--)//正常寫法時j>100,但為減少比較次數j>=i就可以了{times++;product = i*j;if(product>max && is_palindromic(product)){max = product;best_i=i;best_j=j;break;//對于更小的j沒必要比較了,因為其必定小于max}}}//testprintf("%d * %d, call times %d\n", best_i, best_j, times);return max;}注:當完成題目后,對于某些題,官方網站會給出參考答案,在我的博客里不會將官方答案貼出來,僅僅會寫下我自己當時的思路,除非兩者不謀而合。另外,如果你有更好的思路,請留言告訴我,我非常樂意參與到討論中來。?
?
轉載于:https://www.cnblogs.com/zhouyinhui/archive/2011/01/14/1935824.html
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的[Project Euler] 来做欧拉项目练习题吧: 题目004的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 3DMAX室内空间怎么布光 3DMAX室
- 下一篇: MySQL之limit使用