求幂运算的不同发法之间的时间复杂度比较

求幂运算的不同发法之间的时间复杂度比较

求幂运算有多种方法其中每种方法时间复杂度不尽相同

其中递归解法的数学原理为:

\(k^n\) = \(k^{(2) * (\frac{n}{2})}\)

详解如下:

void test(){
    long long result = calculatePower(2, 4);
    printf("the result is %lld\n", result);
}

long long calculatePower(int x, int n){
#if 0 - 此方法最慢
    //O(N)
    int power = x;
    if (n >= 1) {
        for (int i = 0; i < n - 1; i++) {
            power *= x;

            static int calculateCount = 0;
            printf("calculate count is %d\n", calculateCount++);

        }
    }

    NSLog(@"the power is %d", power);

    return power;
#endif

#if 0 - 此方法并没有加快运算速度
    //此做法相当于是个for循环
    //O(N)
    static int calculateCount = 0;
    printf("calculate count is %d\n", calculateCount++);

    if (n == 1) {
        return x;
    }else if(n > 1){
        if (n % 2 == 0) {
            return calculatePower(x, n/2) * calculatePower(x, n/2);
        }else{
            //return calculatePower(x, n/2) * calculatePower(x, n/2) * x;
            return calculatePower(x, n -1) * x;
        }
    }
    return 0;
#endif

#if 1 - 递归处理
    //此方法 OlogN
    static int calculateCount = 0;
    printf("calculate count is %d\n", calculateCount++);

    if (n == 1) {
        return x;
    }else if(n > 1){
        if (n % 2 == 0) {
            return calculatePower(x * x, n/2);
        }else{
            return calculatePower(x, n -1) * x;
        }
    }

    return 0;
#endif


#if 0 - 不使用递归
    //此方法 OlogN
    int power = 1;
    static int calculateCount = 0;

    for (int i = 0; i < n/2; i++) {
        power *= x * x;
        printf("calculate count is %d\n", calculateCount++);
    }

    if (n % 2 != 0) {
        power *= x;
    }

    return power;
#endif
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值