[51nod]1004 n^n的末位数字

给出一个整数N,输出N^N(N的N次方)的十进制表示的末位数字。
 
Input
一个数N(1 <= N <= 10^9)
Output
输出N^N的末位数字
Input示例
13
Output示例
3


快速幂
代码:
#include <iostream>
using namespace std;

#define LL long long
#define Mod 10

LL Pow(LL a, LL n)
{
    int ans = 1;
    while (n) {
        if (n & 1)
            ans = (ans*a)%Mod;
        a = (a*a)%Mod;
        n >>= 1;
    }
    return ans%10;
}

int main()
{
    //freopen("1.txt", "r", stdin);
    int a;
    cin >> a;
    cout << Pow(a, a);

    return 0;
}

解二:

  其实可以通过找规律来确定,n的n次阶乘有如下规律:

4次一循环 所以只用计算1-4次方即可且只计算数字末位

代码:

#include <iostream>
#include <math.h>
#include <stdio.h>
using namespace std;

int main()
{
    //freopen("1.txt", "r", stdin);
    int n;
    cin >> n;
    int a, b;
    a = n % 10;
    b = n % 4;
    if (b == 0)
        b = 4;
    cout << (int)pow(a, b)%10;

    return 0;
}

 

 

 
posted @ 2017-06-24 15:01  whileskies  阅读(156)  评论(0编辑  收藏  举报