HDU-1061-Rightmost Digit(快速幂)

  • 快速幂(本代码中的^表示次幂不是异或)
    Accepted 1061 0MS 1368K 679 B G++
    #include "bits/stdc++.h"
    using namespace std;
    const int MOD = 10;
    int quick_pow(int n, int m) {
        // 因为1乘任何数都是它本身,所以初始化ans为1 
        int ans = 1;
        while (m != 0) {
            // 如果m是奇数,我们可以视为求ans * n * n ^ (m -1); 
            if (m & 1) {
                // 所以将n乘给ans,使我们要求的结果变成ans * n ^ (m - 1) 
                ans = ans * n % MOD; 
            }
            // 如果m偶数我们要求ans * n ^ m, 而经过上面处理过之后m就算是奇数也变成了偶数,因为减1了
            // 所以n平方, m除2,变成(n ^ 2) ^ (m >> 1); 
            n = n * n % MOD;
            m >>= 1;
        }
        return ans;
    }
    int main() {
        int t, n;
        scanf("%d", &t);
        while (t--) {
            scanf("%d", &n);
            printf("%d\n", quick_pow(n % 10, n));
        }
        return 0;
    }

     

posted @ 2018-09-20 16:33  Jathon-cnblogs  阅读(103)  评论(0编辑  收藏  举报