hdu 1061 快速冪取餘模版裸題


Rightmost Digit

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 51889    Accepted Submission(s): 19634


Problem 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
Hint
In the first case, 3 * 3 * 3 = 27, so the rightmost digit is 7. In the second case, 4 * 4 * 4 * 4 = 256, so the rightmost digit is 6.



第一個方法直接套模版 P26

用大數取模的二進制方法

#include <iostream>
#include <cstring>
using namespace std;
typedef long long ll;
/*
 * hdu 1061
 * by : mazicwong
 * creat on: 2016/12/10
 */

/*
求n的n次方的最後一個數字,直接套模版P28
大數取模
*/
int mod_exp(int a, int b0, int n)  //return a^b0 & n
{
	if (a > n) a %= n;
	int i, d = 1, b[35];
	for (i = 0; i < 35; i++)
	{
		b[i] = b0 % 2;
		b0 /= 2;
		if (b0 == 0) break;
	}//b[i] b[i-1] ...b[0]爲b0的二進制表示
	for (; i >= 0; i--)
	{
		d = (d*d) % n;
		if (b[i] == 1) d = (d*a) % n;
	}
	return d;
}
int main()
{
	int t;
	scanf("%d", &t);
	while (t--)
	{
		int n;
		scanf("%d", &n);
		printf("%d\n", mod_exp(n, n, 10));//return n^n % 10
	}
	return 0;
}


第二個模版

int mod_exp(int a, int b, int c)
{
	int ans = 1;
	a = a%c;
	while (b > 0)
	{
		if (b & 1)
			ans = (ans*a) % c;
		b = b >> 1;
		a = (a*a) % c;
	}
	return ans;
}


兩個模版都一樣,第二個打起來快點,









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