日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

快速求幂算法

發布時間:2023/12/10 编程问答 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 快速求幂算法 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1 #include <stdio.h> 2 #include <math.h> 3 //遞歸算法 4 int recursion(int a,int b) 5 { 6 int tem = 1; 7 if(b==0)return 1; 8 else if(b==1)return a; 9 tem = recursion(a,b>>1); 10 tem = tem*tem; 11 if(b&1) tem = tem * a; 12 return tem; 13 } 14 //循環算法 15 int loop(int a,int b) 16 { 17 int tem=1,ret=a; 18 while(b>0) 19 { 20 if(b&1) tem = tem * ret; 21 ret = ret*ret; 22 b>>=1; 23 } 24 return tem; 25 } 26 int main() 27 { 28 int a,b; 29 while(1) 30 { 31 printf("For a^b input a and b:"); 32 scanf("%d%d",&a,&b); 33 printf("The recursion method:\n"); 34 printf("%d\n",recursion(a,b)); 35 printf("The loop method:\n"); 36 printf("%d\n",loop(a,b)); 37 } 38 return 0; 39 }

原理:

直接乘要做998次乘法。但事實上可以這樣做,先求出2^k次冪:

3 ^ 2 = 3 * 3
3 ^ 4 = (3 ^ 2) * (3 ^ 2)
3 ^ 8 = (3 ^ 4) * (3 ^ 4)
3 ^ 16 = (3 ^ 8) * (3 ^ 8)
3 ^ 32 = (3 ^ 16) * (3 ^ 16)
3 ^ 64 = (3 ^ 32) * (3 ^ 32)
3 ^ 128 = (3 ^ 64) * (3 ^ 64)
3 ^ 256 = (3 ^ 128) * (3 ^ 128)
3 ^ 512 = (3 ^ 256) * (3 ^ 256)

再相乘:

3 ^ 999
= 3 ^ (512 + 256 + 128 + 64 + 32 + 4 + 2 + 1)
= (3 ^ 512) * (3 ^ 256) * (3 ^ 128) * (3 ^ 64) * (3 ^ 32) * (3 ^ 4) * (3 ^ 2) * 3

轉載于:https://www.cnblogs.com/newpanderking/archive/2012/04/25/2470609.html

總結

以上是生活随笔為你收集整理的快速求幂算法的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。