Recursive power function: approach

后端 未结 9 1176
北恋
北恋 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:49

    The code:

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

    does not work because when n is even power is called with n = 2 which is even and then power is called with n = 2 which is even and then power is called with n = 2 ... until ... stack overflow!

    Simple solution:

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

提交回复
热议问题