[HDU] [1061] Rightmost Digit

Problem Description

Loading...

Problem Analysis

If we compute the power normally, we can use Fast Exponentiation

cpp
 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;
}

Using the congruence theorem, we can find the last digit

cpp
 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;
}

Otherwise, finding the pattern and precomputing a table is also a viable approach

cpp
 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;
}

Recommended blog: HDU OJ (HDOJ) Problem 1097: A hard puzzle (Number Theory)

Loading...