繁体   English   中英

如何使用指数递归 function 找到 x^63 的乘法数以及如何证明它的合理性?

[英]How to find the number of multiplications for x^63 using the exponent recursive function and how to justify it?

我如何 go 证明这个算法是 O(log n)?

public static long exponentiation(long x, int n){

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

对方法exponentiation的每个递归调用都是一个乘法步骤 因此,您需要计算递归调用的数量。 有几种方法可以实现这一点。 我选择在方法中添加另一个参数。

public static long exponentiation(long x, int n, int count) {
    if (n == 0) {
        System.out.println("steps = " + count);
        return 1;
    }
    else if (n % 2 == 0) {
        x = exponentiation(x, n / 2, count + 1);
        return x * x; 
    }
    else {
        return x * exponentiation(x, n - 1, count + 1);
    }
}

这是对方法exponentiation的初始调用

exponentiation(2, 63, 0);

当我运行上面的代码时,会打印以下内容

steps = 11

您也可以使用static计数器(无需更改函数原型):

public static long counter = 0;

public static long exponentiation(long x, int n){
    if(n == 0){
        return 1;
    }
    else if (n % 2 == 0){
        x = exponentiation(x, n / 2);
        counter++;
        return x * x; 
    }
    else{
        counter++;
        return x * exponentiation(x, n-1);
    }
}

但是,您需要在每次调用 function 之前重置计数器,即设置counter = 0

理论分析

请注意,您需要向计数器证明它在O(log(n))中。 要证明复杂性,只需要通过查看代码流来找到复杂性项即可。 假设T(n)是计算x^n的乘法次数。 因此,根据书面代码,如果n是偶数,则T(n) = T(n/2) + 1 ,如果n是奇数,则T(n) = T(n-1) + 1 现在,至少在两个连续递归之一中,输入n是偶数。 因此,最多需要2 log(n)才能达到n = 0 因为,对于每个偶数输入,下一个输入将减半。 因此,我们可以得出结论,该算法在O(log(n))中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM