HDU1097 A hard puzzle【快速模幂+数学规律】

A hard puzzle

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 52171 Accepted Submission(s): 19072

Problem Description
lcy gives a hard puzzle to feng5166,lwg,JGShining and Ignatius: gave a and b,how to know the a^b.everybody objects to this BT problem,so lcy makes the problem easier than begin.
this puzzle describes that: gave a and b,how to know the a^b's the last digit number.But everybody is too lazy to slove this problem,so they remit to you who is wise.

Input
There are mutiple test cases. Each test cases consists of two numbers a and b(0<a,b<=2^30)

Output
For each test case, you should output the a^b's last digit number.

Sample Input
7 66
8 800

Sample Output
9
6

Author
eddy

问题链接HDU1097 A hard puzzle
问题简述:(略)
问题分析
    这个问题是计算a^b的最后1位,标准的快速模幂模板题。
    然而,还有一种利用数学规律实现的方法。实际上,本题就是要计算a^b%10,所以结果只跟a%10(a的最低位个位有关),然后就是寻找循环规律:
0: 0^n%10 = 0
1: 1^n%10 = 1
5: 5^n%10 = 5
6: 6^n%10 = 6
4: 4^(2k)%10 = 6
4: 4^(2k+1)%10 = 4
9: 9^(2k)%10 = 1
9: 9^(2k+1)%10 = 9
2: 2^(4k)%10 = 6
2: 2^(4k+1)%10 = 2
2: 2^(4k+2)%10 = 4
2: 2^(4k+3)%10 = 8
3: 3^(4k)%10 = 1
3: 3^(4k+1)%10 = 3
3: 3^(4k+2)%10 = 9
3: 3^(4k+3)%10 = 7
......

程序说明:(略)
参考链接:(略)
题记:(略)

AC的C语言程序如下:

/* HDU1097 A hard puzzle */

#include <stdio.h>

#define D9 9
int cycle[] = {1, 1, 4, 4, 2, 1, 1, 4, 4, 2};
int ans[][4] = {
    {0},
    {1},
    {6, 2, 4, 8},
    {1, 3, 9, 7},
    {6, 4},
    {5},
    {6},
    {1, 7, 9, 3},
    {6, 8, 4, 2},
    {1, 9}
};

int main(void)
{
    int a, b;
    while(scanf("%d%d", &a, &b) != EOF)
        printf("%d\n", ans[a % 10][b % cycle[a % 10]]);

    return 0;
}

AC的C语言程序如下:

/* HDU1097 A hard puzzle */

#include <stdio.h>

typedef long long LL;

// 快速模幂
LL powmod(LL x, LL n, LL m)
{
    LL result = 1;
    for(; n; n >>= 1) {
        if(n & 1) {
            result *= x;
            result %= m;
        }
        x *= x;
        x %= m;
    }

    return result;
}

int main(void)
{
    int a, b;
    while(scanf("%d%d", &a, &b) != EOF)
        printf("%lld\n", powmod(a, b, 10));

    return 0;
}

posted on 2018-12-30 21:32  新海岛Blog  阅读(183)  评论(0)    收藏  举报

导航

// ... runAll: function() { this.resetPreCode(); hljs.initHighlightingOnLoad(); // 重新渲染,添加语法高亮 hljs.initLineNumbersOnLoad(); // 为代码加上行号 } // ...