快速求幂(位运算)

来源:互联网 发布:nba95年总决赛数据 编辑:程序博客网 时间:2024/06/14 09:17
#include<iostream>//这个程序采用位运算来处理,更高效 #include<cstdio>using namespace std;int pow4(int x, int n){    int result;    if (n == 0)        return 1;//除0外,自然数的0次方都得1     else    {        while ((n & 1) == 0)//(位运算)偶数         {            n >>= 1;            x *= x;        }    }    result = x;    n >>= 1;//因为上部分都是判断完才开始移动,所以需要加上这一步     while (n != 0)    {            x *= x;        if ((n & 1) != 0)//最终都会落到1上,从result得到答案             result *= x;        n >>= 1;    }    return result;}int main(){int a,b;cin>>a>>b;cout<<pow4(a,b);return 0;}

0 0