第二次周赛HDU-1061题解

问题链接:HDU-1061

问题简述

第一行输入一个数n,下面有n组数据,每组数据输入一个数m(1<=m<=1,000,000,000),然后输出mm的个位数。

思路

当时在周赛时不知道快速幂算法,最后是找规律写出来的,后来百度学了一下快速幂,可以用快速幂算法来解。

AC通过的C++语言程序如下:
找规律:

#include<iostream>
#include<cmath>
using namespace std;
int main()
{
	int n;
	cin >> n;
	for (int i = 0; i < n; i++)
	{
		int x, a, b, c, d;
		cin >> x;
		a = x % 10; b = x % 4;
		if (b == 0) b = 4;
		c = pow(a, b);
		d = c % 10;
		cout << d << endl;
	}
	return 0;
}

快速幂:

#include<iostream>
int f(int,int,int);
using namespace std;
int main()
{
	int n;
	cin >> n;
	for (int i = 0; i < n; i++)
	{
		int m;
		cin >> m;
		cout << f(m, m, 10) << endl;
	}
	return 0;
}
int f(int a, int b, int c)
{
	int k = 1;
	a = a % c;
	while (b>0)
	{
		if (b % 2 != 0)
			k = (k*a) % c;
		b = b / 2;
		a = (a*a) % c;
	}
	return k;
}

猜你喜欢

转载自blog.csdn.net/weixin_43970556/article/details/85075864