您的位置:首页 > 其它

hdu1061-Rightmost Digit(附20循环的规律解法和附快速幂简单原理)

2013-06-09 15:45 323 查看
http://acm.hdu.edu.cn/showproblem.php?pid=1061

1.快速幂实现a^N
求3^999(a=3,N=999):3 ^ 999 = 3 * 3 * 3 * … * 3,直接乘要做998次乘法。
快速幂方法实质使用了二分法进行时间优化:
 tmp+   =   tmp-*    a-;
3 ^ 1  =    3*    1
3 ^ 2  = (3 ^ 1)*
(3 ^ 1)
3 ^ 4  = (3 ^ 2) *(3 ^ 2)
…………
3 ^ 256 = (3 ^ 128) * (3 ^ 128)
3 ^ 512 = (3 ^ 256) * (3 ^ 256)
==>
3 ^ 999 
= (3 ^ 512) * (3 ^ 256) * (3 ^ 128) * (3 ^ 64) * (3 ^ 32) * (3 ^ 4) * (3 ^ 2) * 3 
只做16次乘法。
将999转为2进制数:1111100111
1    1   1   1  1 0 0 1 1 1
512 256 128 64 32 0 0 4 2 1
各个位上的值即为需要进行乘积的标志。
 

#include "stdio.h"
#include "string.h"
#include "stdlib.h"
#include "math.h"
#include "algorithm"
#include "iostream"

using namespace std;

#define INT __int64
int Pow( INT n )
{
int temp = n % 10 ;
int ans = 1 ;
while( n )
{
if( n % 2 == 1 )
{
n-- ;
ans *= temp;
ans %= 10 ;
}
else
{
n /= 2 ;
temp *= temp ;
temp %= 10 ;
}
ans %= 10 ;
}
return ans ;
}

int main()
{
INT n ;
int Case ;
cin >> Case ;
while( Case-- )
{
cin >> n ;
cout << Pow( n ) << endl ;
}
return 0;
}


 

下面是发现没20个数据存在循环,之前没有将num[ 0] 赋值为0 ,总是WA,还怀疑规律是不是错了,但是突然发现20的倍数mod20会为0

#include<iostream>
#include<cstdio>
#include<cmath>

using namespace std;

int main()
{
__int64 n ;
int a , b , num[ 50 ] ;
int i ;
num[ 0 ] = 0 ;
for(i = 1 ; i <= 20 ; i++ )
{
a = i ;
b = 1 ;
while ( a-- )
{
b = b * i % 10 ;
}
num[ i ] = b ;
}
int Case ;
cin >> Case;
{
while( Case-- )
{
cin >> n ;
n = n % 20 ;
//	cout << n << endl ;
cout << num[ n ] << endl ;
}
}
return 0 ;
}


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