HDU 1061 Rightmost Digit (四則運算求餘,快速冪)

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

就是讓你輸入n^n的個位數即模除10

關於大數求餘的一些技巧,一般那個大整數都是由一些小整數經過運算得到的,而四則運算的求餘公式如下(a b均大於等於0):

1.(a+b)%n=((a%n)+(b%n))%n

2.(a-b)%n=((a%n)-(b%n)+n)%n

3.(a*b)%n=((a%n)*(b%n))%n

4.(a/b)%n=((a%n)*(b^-1%n))%n


有了這些公式我們可以得知n^n%10=(n%10)^n%10,而一位整數的n次冪的個位數是一個循環序列,循環區間不超過4。所以基本上可以化爲一個簡單的冪運算了。


而冪運算我們一般需要自己寫一個快速冪運算函數,期間如果需要求餘,也可以配合寫進去

快速冪求餘函數模板:

template<class T,class D>
T qpow(T a,D n,int mod)
{
	if(n==0) return 1;//這裏的返回值取決於T的類型,如果是矩陣要返回單位矩陣
	T ans=qpow(a,n/2,mod);
	ans=ans*ans%mod;
	if(n%2!=0) ans=ans*a%mod;
	return ans; 
}


本題代碼

#include<stdio.h>

int qpow(int a,int n,int mod)
{
	if(n==0) return 1;
	int ans=qpow(a,n/2,mod);
	ans=ans*ans%mod;
	if(n%2!=0) ans=ans*a%mod;
	return ans; 
}

int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		int n,m;
		scanf("%d",&n);
		m=n % 10;
        n=n%4==0?4:n%4;
		printf("%d\n",qpow(m,n,10));
	}
	return 0;
} 


思路就是化n^n%10爲(n%10)^(n%4)%10,其中(n%4)要注意4的時候應該置爲4而不是0








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章