|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 |
A^B的后三位数只与A的后三位有关,用二分求幂求得A^B,在计算中间结果时仅保留后三位,快速求得A的B次方//一般方法Int ans=1;for(int
i=1;i<=b;i++)ans*=a;//二分求幂#include <iostream>#include <stdio.h>int main(){ int
a,b; while(scanf("%d%d",&a,&b)!=EOF) { if(a == 0 && b == 0) break; int
ans = 1; while(b != 0)//对B转换二进制过程未结束 { if(b%2 == 1)//若当前二进制位为1,需累乘A的2^K次至变量ans,其中2^K为二进位的权重 { ans *= a;//最终结果累乘A } b /= 2; a *= a;//求下一位权重,A求其平方,即从A的1次方开始,依次计算A的2次,4次 } printf("%d\n",ans); } return
0;} |
原文:http://www.cnblogs.com/Xilian/p/3657945.html