幻数linux
程序语句:
问题说明:
amagicnumberisdefinedasanumberwhichcanbeexpressedasapowerof5orsumofuniquepowersof5. firstfewmagicnumbersare 5、25、30 ) 56525
幻数被定义为可以表示为5的幂或5的幂之和的数字。 第一个数为5,25,30 (525 ),125,130 (125 )。
Given the value of n,find the nth Magic number。
给定n的值,找到第n个幻数。
Example:
例如:
input : n=1output :5 input : n=2output :25 input : n=3output :30 solution 3:
解:
onenaveapproachistouseasettostorethesequenceofmagicnumbers.westorethepowersof 5、 andthentryallcombinationsumbetweentheuniquepowersandinsertthesumsintothesetifitalreadynotthere.setsortststheionsertionandsoas 微信公众号/公众号。
一个简单的方法是使用一系列守恒幻数序列。 保存5的幂,尝试所有唯一的幂之间的组合,如果还没有,请将和插入到集合中。 由于Set对插入进行排序,因此当集合大小达到n时,可以输出集合中的最后一个数字/集合中的最大编号。
findfindingsumsbetweendifferentcombinationsaretediousandn-phardproblemifsolvedingeneral。
综合解决,不同组合之间的总和将是一个枯燥、NP困难的问题。
sothesolutionissomethingdifferent
因此,解决方案不同。
let ' smanuallycomputethemagicnumbersfirstandtrytoobservethegeneratedsequenceasawhole。
首先手动计算幻数,然后观察整个生成的序列。
firstoneisobviously5next would be25 nowwecanfindacombinationsumandthat’sonlyone,25 (30 noothercombinationspossibletillnow.) we can some only unique powers of 5) next will be 125 thenwehavefewcombinationslike 5125=13025125=150525125=155 nomorecombinationspossibleuptonownextwouldbe 625 then 63025625=650525625=655125625=75525125625=77525125125625=780 nomo recombination uptonownextwillbe5^4=sequence is 3360525301251301501501556256306557507507507507557753125 . thisisactuallysimilarpatternlikebinarynumbers 001001001000011 0000011 010101010100010100010000 ----------------------------------- - I ) where is indexed-1 thebitpositioncountedfromlsbso,0001=0*pow (5,4 )0*pow ) 5,3 )0* pow ) 5,2 )1*pow(5 weneedtofindnthmagicnumber.wehavebinaryrepresentationofnwhatweneedtodoistoconvertthebasetonumbertobasepow (5, I ) number note : thismayseemtobesameasconvertingtobase5number, butthisisnot.for base5numberiwouldhavestartfrom0forlsbthat ' snotabigdeal.# dfinemax 10 ^ 97 }@media(min-width:1025px ).minheight ) min-height:90px; }.minheight { min-height 3360250 px; }@media(min-width:1025px ).minheight ) min-height:90px; } } Algo:
算法:
1. Declare pro=1; 2. Declare answer=0; 3.while(nisnot0) pro=) pro*5) %max; //pow(5,I ) if ) N1 )//currentlsbis1answer=(answer pro ) %max; END IF n=n1; //right shift n,similartodivingby2end while4. return answer; C implementation:
C实现:
# include bits/stdc.husingnamespacestd; # definemax 100000007 longlongintmagicno (intn ) {long long int pro=1; 长龙安swer=0; while(n ) {pro=(pro*5) %max; //pow(5,I ) if ) N1 )//currentLSB1answer=(answerpro ) %max; n=n1; //rightshiftby1bit } return answer; (}int main ) ) {int n; 计数输入n :n '; scanf('%d ',n ); coutn' th magic no is: '; coutmagicno(n ) endl; 返回0; } Output
出口量
entern :55 thmagicnois :130翻译自:3359 www.include help.com/ICP/find-nth-magic-numbers.aspx
幻数linux