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

HDU_1061:Rightmost Digit

时间:2015-04-09 23:45:07      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

Problem Description
Given a positive integer N, you should output the most right digit of N^N.
 
Input
The input contains several test cases. The first line of the input is a single integer T which is the number of test cases. T test cases follow.
Each test case contains a single positive integer N(1<=N<=1,000,000,000).
 
Output
For each test case, you should output the rightmost digit of N^N.
 
Sample Input
2 3 4
 
Sample Output
7 6
Hint
In the first case, 3 * 3 * 3 = 27, so the rightmost digit is 7. In the second case, 4 * 4 * 4 * 4 = 256, so the rightmost digit is 6.
 
最先想到的是一个一个算,但是由于数据范围太大,O(n^2)的时间复杂度对于n = 10亿时,10亿^10亿次乘法运算实在是不能忍受的。因此下面的程序超时(Time Limit Exceeded)。
#include<stdio.h>
int main(void)
{
    int cases, n, copy_n, result;
    scanf("%d", &cases);
    while(cases--)
    {
        scanf("%d", &n);
        copy_n = n;
        n = n%10;
        result = 1;
        while(copy_n--)
        {
            result = (result*n)%10;
        }
        printf("%d\n", result);
    }
    
    return 0;
}

下面,快速幂一来就AC了:

#include<stdio.h>
int my_power(int m, int n); // 求m的n次方的尾数
int main(void)
{
    int cases, n;
    scanf("%d", &cases);
    while(cases--)
    {
        scanf("%d", &n);
        printf("%d\n", my_power(n, n));
    }
    
    return 0;
}

int my_power(int m, int n)
{
    m = m%10;
    if(n == 1)
        return m;
    if(n%2 == 0)
        return ( my_power(m*m, n/2) ) % 10;
    else
        return ( my_power(m*m, n/2)*m ) % 10;
}

可以看到,快速幂的时间复杂度是O(logn),n = 10亿时,大约32次递归调用就能出结果,效率极大的提高了。

HDU_1061:Rightmost Digit

标签:

原文地址:http://www.cnblogs.com/xpjiang/p/4412881.html

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