码迷,mamicode.com
首页 > Web开发 > 详细

A - Rightmost Digit

时间:2019-07-17 23:08:30      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:理解   def   space   col   个人   mic   return   nbsp   技术   

技术图片

技术图片

 

思路:

运用快速幂。

 

代码:

#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个人理解为是大部分按照题目要求需要除以的数,为了防止溢出。

A - Rightmost Digit

标签:理解   def   space   col   个人   mic   return   nbsp   技术   

原文地址:https://www.cnblogs.com/123-d/p/11204268.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!