简体   繁体   English

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

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

How would I go about justifying this algorithm is O(log n)?我如何 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);
    }
}

Each recursive call to method exponentiation is a multiplication step .对方法exponentiation的每个递归调用都是一个乘法步骤 Hence you need to count the number of recursive calls.因此,您需要计算递归调用的数量。 There are several ways to achieve this.有几种方法可以实现这一点。 I chose to add another parameter to the method.我选择在方法中添加另一个参数。

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);
    }
}

Here is the initial call to method exponentiation这是对方法exponentiation的初始调用

exponentiation(2, 63, 0);

When I run the above code, the following is printed当我运行上面的代码时,会打印以下内容

steps = 11

You can use a static counter as well (without changing the prototype of the function):您也可以使用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);
    }
}

However, you need to reset the counter before calling the function each time, ie, set counter = 0 .但是,您需要在每次调用 function 之前重置计数器,即设置counter = 0

Theoretical Analysis理论分析

Note that you need to the counter to prove that it is in O(log(n)) .请注意,您需要向计数器证明它在O(log(n))中。 To prove the complexity, just you need to find the complexity term by looking at the flow of the code.要证明复杂性,只需要通过查看代码流来找到复杂性项即可。 Suppose T(n) is the number of multiplications for computing x^n .假设T(n)是计算x^n的乘法次数。 So, based on the written code, T(n) = T(n/2) + 1 , if n is even, and T(n) = T(n-1) + 1 , if n is odd.因此,根据书面代码,如果n是偶数,则T(n) = T(n/2) + 1 ,如果n是奇数,则T(n) = T(n-1) + 1 Now, at least in one of two consecutive recursions, input n is even.现在,至少在两个连续递归之一中,输入n是偶数。 Therefore, at most 2 log(n) is required to reach to n = 0 .因此,最多需要2 log(n)才能达到n = 0 Because, for each even input, the next input will be halved.因为,对于每个偶数输入,下一个输入将减半。 So, we can conclude that the algorithm is in O(log(n)) .因此,我们可以得出结论,该算法在O(log(n))中。

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

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