【51nod】1004 n^n的末位数字

1004 n^n的末位数字 

题解:

由于题目是问末尾数字,所以我们可以直接对n模10,用最后一位数字进行运算。

我们可以列一个表格观察末尾数字自身乘积变化。

0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1
2 4 8 6 2 4 8 6 2 4
3 9 7 1 3 9 7 1 3 9
4 6 4 6 4 6 4 6 4 6
5 5 5 5 5 5 5 5 5 5
6 6 6 6 6 6 6 6 6 6
7 9 3 1 7 9 3 1 7 9
8 4 2 6 8 4 2 6 8 4
9 1 9 1 9 1 9 1 9 1

根据观察,末尾数字自身乘积最多4次,其所得积末尾数字就变回本身。

很快,最先想到的就是直接用二维数组存放。

#include <cstdio>
#include <cmath>
using namespace std;
int n;
int ans[10][4] = {{0,0,0,0}, {1,1,1,1}, {2,4,8,6}, {3,9,7,1}, {4,6,4,6},
                 {5,5,5,5}, {6,6,6,6}, {7,9,3,1}, {8,4,2,6}, {9,1,9,1}};
int main(){
    scanf("%d", &n);
    printf("%d", ans[n%10][(n-1)%4]);
//注意,由于数组跟取模的原因,这里用(n-1)%4而不是直接n%4
    return 0;
}

或者直接敲代码

#include <cstdio>
#include <cmath>
using namespace std;
int n, temp;
int main(){
    scanf("%d", &n);
    int temp = n % 4;
    if(temp==0)
        temp = 4;
    n %= 10;
    int ans = pow(n, temp);
    printf("%d", ans%10);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Zy_Ming/article/details/82053798