Recursive power function: approach

后端 未结 9 1187
北恋
北恋 2020-12-18 15:24

I\'m programming for a while now(beginner), and recursive functions are a somewhat abstract concept for me. I would not say I\'m stuck, program works fine, I\'m just wonderi

9条回答
  •  北荒
    北荒 (楼主)
    2020-12-18 15:50

    You want to avoid using pow(), right? So you used power() instead, leading to a recursive call within the argument list. This led to a segmentation fault.

    First of all, let us understand the cause of the problem. I did a pen and paper run of the algorithm and the result is pretty interesting. It turns out that for any values of x and n, after a certain number of recursions one always ends up getting power(1, 2). This also means that power(1, 2) also leads to power (1, 2) after a certain number of recursions. Thus, this power() within a power() leads to an infinite recursion and thus the stack overflow.

    Now, to your question. Yes, this can be done without using pow() because pow(a, 2) can simply be written as a*a. So, here is a slight modification to your code:

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

    But then, why do it this way? A more efficient way would be as follows.

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

    This reduces the number of recursions needed, making the code more time and space efficient. Hope this helps!

提交回复
热议问题