HDU1061 - Rightmost Digit (二分幂取模)

来源:互联网 发布:英语口语app软件 编辑:程序博客网 时间:2024/05/22 14:51

题目链接

  • 思路
  • 代码

思路

需要取出 NN 的最后一位,就相当与对 10 取模。

二分幂取模实际上就是利用分治的思想。

nn=n(n/2)n(n/2), 如果 n&1==1 还需要再乘上一个 n。

代码

#include <cstdio>#include <cmath>using namespace std;int pow_mod(int a, int b, int mod){    if(b==0) return 1;    int ans = pow_mod(a, b>>1, mod);    ans = ans * ans % mod;    // 此处可能溢出,也可直接用 long long    if(b&1) ans = ans * (a % mod) % mod;    return ans;}int main(){    int num, t;    scanf("%d", &t);    while(t--)    {        scanf("%d", &num);        printf("%d\n", pow_mod(num, num, 10));    }    return 0;}
0 0
原创粉丝点击