Fast Power Algorithm / Fast Matrix Exponeitation

@vrqq  November 14, 2017

Part 1 Just only number.

We know xa+b = xa * xb.
e.g.
513 = 58 x 54 x 51
So we have this code:

long double myPow(long double x, int pow) {
    bool flag=0;
    if (pow<0)
        flag=1, pow=-pow;
    long long bit=1;
    long double baseNum=x;
    long double ans=1;
    while (bit<=pow) {
        if (bit&pow)
            ans *= baseNum;
        bit <<= 1;
        baseNum *= baseNum;
    }
    if (flag)
        return (long double)(1.0)/ans;
    return ans;
}

Part 2 Matrix

same as part 1.


添加新评论