Re: [問題] a的b次方實作時間logb之遞迴寫法

看板C_and_CPP作者 (下班後才下棋)時間14年前 (2010/03/24 23:42), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串2/6 (看更多)
※ 引述《conan77420 (人生就是不停的戰鬥)》之銘言: : a的b次方計算時間在logb內完成 : 這題好像之前有在板上看過,但好像沒有遞迴版的 : 非遞迴的寫法我自己寫的如下: : #include<iostream.h> : using namespace std; : int fastpow(int ,int ); : int main() : { : int num=0, pow=0; : cout<<"Enter num:"; : cin>>num; : cout<<"Enter pow:"; : cin>>pow; : cout<<fastpow(num,pow); : system("pause"); : } : int fastpow(int a,int b) : { : int temp=1; : while(b!=0) : { : if(b&1) : {temp=temp*a;} : a=a*a; : b=b>>1; : } : return temp; : } : ================================= : 造裡說非遞迴出的來〝遞迴〞應該就出的來 : 無奈可能非遞迴沒寫得很好,遞迴我實在想不出來要怎麼寫才漂亮 : 請教大家 示意一下就好 my_pow(int a, int b) half <- my_pow(a, ceil(b/2)) if(b&1) return half * half * a; else return half * half; -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.112.30.49
文章代碼(AID): #1BgZBR6V (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1BgZBR6V (C_and_CPP)