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