您的位置:首页 > 其它

HDOJ--Rightmost Digit

2016-05-31 21:10 369 查看
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.

最初想法:由于只求个位数,所以暴力一把,将每个数字的个位相乘。

#include <iostream>
#include <string>
using namespace std;

int getRightDigit(string n)
{
return n[n.length() - 1] - '0';
}

int main()
{
int t;
cin >> t;
for (int i = 0; i < t; ++i)
{
string n;
cin >> n;

int result = 1;
int len = atoi(n.c_str());
string tmp = n;
for (int j = 1; j < len; ++j)
{
result = getRightDigit(tmp)*getRightDigit(n);
char buf[100];
sprintf(buf, "%d", result);
tmp = buf;
result = getRightDigit(tmp);
}
cout << result << endl;
}
return 0;
}


最初的结果:这种题一般暴力都没好下场。。结果当然是TLE啦~~

经过一些材料收集后发现有种叫快速幂的算法能够提高幂运算的效率,下面来看看快速幂法是个什么鬼。

举个例子 4^ 999 = 4 * 4 * 4 * … * 4

直接乘要做998次乘法。但事实上可以这样做,先求出4^k次幂:

4 ^ 999

= 4 ^ (512 + 256 + 128 + 64 + 32 + 4 + 2 + 1)

= (4 ^ 512) * (4^ 256) * (4 ^ 128) * (4 ^ 64) * (4 ^ 32) * (4 ^ 4) * (4 ^ 2) * 4

这样只要做16次乘法。即使加上一些辅助的存储和运算,也比直接乘高效得多(尤其如果这里底数是成百上千位的大数字的话)。

我们发现,把999转为2进制数:1111100111,其各位就是要乘的数。这提示我们利用求二进制位的算法(其中mod是模运算):

REVERSE_BINARY(n)

1 while (n > 0)

2 do output (n mod 2)

3 n ← n / 2

这个算法给出正整数n的反向二制进位,如6就给出011(6的二进制表示为110)。事实上这个算法对任意的p进制数是通用的,只要把其中的2换成p就可以了。

如何把它改编为求幂运算?我们发现这个算法是从低位向高位做的,而恰好我们求幂也想从低次幂向高次幂计算。而且我们知道前面求出的每个4^k次幂只参与一次乘法运算,这就提示我们并不把所有的中间结果保存下来,而是在计算出它们后就立即运算。于是,我们要做的就是把输出语句改为要做的乘法运算,并在n减少的同时不断地累积求4^k次幂。

算法流程:

POWER_INTEGER(x, n)

1 pow ← 1

2 while (n > 0)

3 do if (n mod 2 = 1)

4 then pow ← pow * x

5 x ← x * x

6 n ← n / 2

7 return pow

不难看出这个算法与前面算法的关系。在第1步给出结果的初值1,在while循环内进行运算。3、4中的if语句就来自REVERSE_BINARY的输出语句,不过改成了如果是1则向pow中乘。5句则是不断地计算x的x^k次幂,如对前面的例子就是计算4^2、4^4、4^8、…、4^512。

应该指出,POWER_INTEGER比前面分析的要再多做两次乘法,一次是向pow中第一次乘x,如4^1也要进行这个乘法;另一次则是在算法的最后,n除以2后该跳出循环,而前面一次x的自乘就浪费掉了。另外,每趟while循环都要进行一次除法和一次模运算,这多数情况下除法和模运算都比乘法慢许多,不过好在我们往往可以用位运算来代替它。

根据上面的快速幂算法,这题可以这样撸

#include <iostream>
#include <string>
using namespace std;

int main()
{
int t;
cin >> t;
for (int i = 0; i < t; ++i)
{
int n;
cin >> n;
int tmp = n % 10;       //防止溢出,即n的个位
int result = 1;
while (n)
{
if (n&1)            //若n为奇数
{
result *= tmp;
result %= 10;
}
tmp *= tmp;
tmp %= 10;
n /= 2;
}
cout << result << endl;

}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  HDOJ 快速幂