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

来源:互联网 发布:淘宝店铺付费推广 编辑:程序博客网 时间:2024/06/06 07:39

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 __int64int 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 ;}


 

原创粉丝点击