首页 > 其他 > 详细

快速幂

时间:2018-10-20 15:20:28      阅读:120      评论:0      收藏:0      [点我收藏+]

求x的p次方对m取余的算法,运用了分治算法。

代码:

 1 #include <iostream>
 2 using namespace std;
 3 int main()
 4 {
 5     int x = 10, p = 4, m = 17;
 6     int result = 1;
 7     while (p > 0)
 8     {
 9         if (p % 2 == 1) result *= x % m;
10         p /= 2;
11         x = x * x%m;
12     }
13     cout << result;//pow(x,2)%m=pow(x%m,2)%m
14 }

关键词:x^p=pow(x^2,p/2)(p为偶数),x^p=x*pow(x^2,(p-1)/2)(p为奇数)

快速幂

原文:https://www.cnblogs.com/ljy1227476113/p/9821715.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!