【杭电】[1061]Rightmost Digit

文章字数:214

问题描述

Rightmost Digit

问题分析

如果正常求幂则可使用快速幂

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
int pow4(int a,int b)
{
    int r=1,base=a;
    while(b!=0)
    {
        if(b&1)
            r*=base;
        base*=base;
        b>>=1;
    }
    return r;
}

运用同余定理可求出最后一位数字

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#include<stdio.h>
int pow(int a,int b) {
	int r=1,base=a%10;
	while(b!=0) {
		if(b%2)
			r=r*base%10;
		base=base*base%10;
		b/=2;
	}
	return r;
}
int main() {
	int T;
	scanf("%d",&T);
	while(T--) {
		int n;
		scanf("%d",&n);
		printf("%d\n",pow(n,n));
	}
	return 0;
}

否则的话找规律打表也是个方法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#include<stdio.h>
int res[4][10]= {
	{0,1,6,1,6,5,6,1,6,1},
	{0,1,2,3,4,5,6,7,8,9},
	{0,1,4,9,6,5,6,9,4,1},
	{0,1,8,7,4,5,6,3,2,9}
};
int main() {
	int T;
	scanf("%d",&T);
	while(T--) {
		int n;
		scanf("%d",&n);
		printf("%d\n",res[n%4][n%10]);
	}
	return 0;
}

推荐博客: 杭电OJ(HDOJ)1097题:A hard puzzle(数论)

该内容采用 CC BY-NC-SA 4.0 许可协议。

如果对您有帮助或存在意见建议,欢迎在下方评论交流。

加载中...