快速幂(转自百度百科 自用)

来源:互联网 发布:淘宝客服周总结 编辑:程序博客网 时间:2024/05/29 07:27

把b转换成二进制数。
该二进制数第i位的权为
例如
11的二进制是1011
11 = 2³×1 + 2²×0 + 2¹×1 + 2º×1
因此,我们将a¹¹转化为算

二分求幂(一般)

int pow2( int a, int b ){    int r = 1, base = a;    while( b != 0 )    {        if( b % 2 )            r *= base;        base *= base;        b /= 2;    }    return r;}

快速求幂(更高效率的位运算法)

int pow4(int x, int n){    int result;    if (n == 0)        return 1;    else    {        while ((n & 1) == 0)        {            n >>= 1;            x *= x;        }    }    result = x;    n >>= 1;    while (n != 0)    {            x *= x;        if ((n & 1) != 0)            result *= x;        n >>= 1;    }    return result;}


0 0
原创粉丝点击