首页 > 其他 > 详细

POJ 1995 Raising Modulo Numbers (快速幂)

时间:2017-08-22 15:14:55      阅读:221      评论:0      收藏:0      [点我收藏+]

题意:技术分享

思路:

对于每个幂次方,将幂指数的二进制形式表示,从右到左移位,每次底数自乘,循环内每步取模。

#include <cstdio>

typedef long long LL;

LL Ksm(LL a, LL b, LL p) {
  LL ans = 1;
  while(b) {
    if(b & 1) {
      ans = (ans * a) % p;
    }
    a = (a * a) % p;
    b >>= 1;
  }
  return ans;
}


int main() {
  LL p, a, b;
  int T;
  int n;
  scanf("%d", &T);
  while(T--) {
    scanf("%lld%d", &p, &n);
    LL ans = 0;
    while(n--) {
      scanf("%lld%lld", &a, &b);
      ans = (ans + Ksm(a, b, p)) % p;
    }
    printf("%lld\n", ans);
  }
  return 0;
}

POJ 1995 Raising Modulo Numbers (快速幂)

原文:http://www.cnblogs.com/demian/p/7411586.html

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