1. 程式人生 > >ACM數論 求冪乘

ACM數論 求冪乘

求冪 http ima pow 舉例 ron 分享 cnblogs 反復平方法

反復平方法

技術分享

____________________________________________________________________________________________________________________________

pow(x,n)

當n==0時

函數等於1;

當n==偶數時

函數等於pow(x^2,n/2);

當n==奇數時

函數等於pow(x^2,n/2)*x;

舉例子

3^21

3^21=(3*3)^10*3

9^10=(9^9)^5

81^5=(81*81)^2*81

6561^2=(6521*6521)

___________________________________________________________________________________________________________________________

pos(x,n)

if n==0

return 1

res=pow(x^x,n/2)

if(n是奇數)

res=res*x

return res

ACM數論 求冪乘