A - Rightmost Digit

 

思路:

运用快速幂。

 

代码:

#include <iostream>
#include <stdio.h>

using namespace std;
typedef long long LL;

void quick_pow(int x)
{
    int ans = 1, y = x;
    x = x % 10;
    while (y)
    {
        if (y & 1)
            ans = (ans * x) % 10;
        y >>= 1;
        x = (x * x) % 10;
    }

    printf ("%d\n", ans);
}
int main()
{
    int a;
    while (cin >> a && a)
    {
        for (int i = 1; i <= a; i++)
        {
            LL b;
            cin >> b;
            quick_pow(b);
        }
    }

    return 0;
}

 

总结:

需要防止溢出。

void quick_pow(int x, int y, int mod)
{
    int ans = 1;
    x = x % 10;
    while (y)
    {
        if (y & 1)
            ans = (ans * x) % mod;
        y >>= 1;
        x = (x * x) % mod;
    }

    printf ("%d\n", ans);
}

a^b 求个位的数字 中需要除以10,至于其他题目看题目要求。

每个数都除以10是为了防止溢出

 

这里的mod个人理解为是大部分按照题目要求需要除以的数,为了防止溢出。

posted @ 2019-07-17 22:52  question-maker  阅读(167)  评论(0编辑  收藏  举报