Rightmost Digit(运用快速幂算法或者找规律的方法)

原题点击获取,嘻嘻
要求:Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)

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.

Author

Ignatius.L

Recommend

We have carefully selected several similar problems for you: 1021 1008 1019 1071 1108

问题简述:
一开始依旧是记得ACM几乎必备的循环输入!!(就是别忘了输入例子数后,要实现输入足够例子后能够结束程序)
回到正题!!乍一看的字面意思:输入一个N值,计算N的N次方,然后把计算得出的这个数的个位数字输出(其实怎么可能出一道这么简单的题目…),即使把类型改为long long ,程序也应该会超时的。错了很多次后第一次我是找到规律来做出的这道题,再看发现的字面意思:那个N的范围你再看看,你再想想计算N的N次方是得到的值,是不是超大的!!(N可以用int类型,可是N的N次方的值用int怕会不够),所以这不是简单的求幂题!!于是考完周试后知道原来是用快速幂…具体可以参考一下烟波煮雨的博客,如果不理解当然也可以记下来,嘻嘻嘻,不过理解至上。

通过后期的努力VJ通过的快速幂求法的代码:

#include<iostream>
using namespace std;         
long long poww(long long a, long long b, long long c)
{
	long long ans = 1;
	a = a % c;
	while (b > 0)
	{
		if (b % 2 == 1) ans = (ans*a) % c;
		b = b / 2;
		a = (a*a) % c;
	}
	return ans;
}
int main()
{
	long long a;
	int T;
	cin >> T;
	while (T--)
	{
		scanf_s("%lld", &a);
		int n=a % 10;
		printf("%lld\n", poww(n, a,10));
	}
	return 0;
}

如果还是不懂快速幂也没有关系,可以看看Karen_Yu_的博客。

上面我有提到我一开始是找规律的方法的做出了赛题,其实在计算本上计一下,会发现这个尾数在20以内循环出现,{0,1,4,7,6,5,6,3,6,9,0,1,6,3,6,5,6,7,4,9},就是这个20个数字会不断的出现。

VS通过的找规律的代码:

#include <iostream>
#include<math.h>
using namespace std;
int main()
{
	int a[100] = { 0,1,4,7,6,5,6,3,6,9,0,1,6,3,6,5,6,7,4,9 };
	int T, N;
	cin >> T;
	while (T--&&cin>>N)
	{
		int j, p;
		j = N % 20;
		p = a[j];
		printf("%d\n", p);
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_43697280/article/details/85109216