Rita li

You give me a future, I love you the whole once

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
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;
}

  

posted on 2014-04-11 09:19  Rita li  阅读(497)  评论(0编辑  收藏  举报