Recursive power function: approach

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

    When rewriting your function, don't lose sight of the main benefit of recursion in this case, which is to reduce the number of multiplication operations required. For example, if n = 8, then it is much more efficient to compute x * x as val1, then val1 * val1 as val2, and the final answer as val2 * val2 (3 multiplications) than to compute x * x * x * x * x * x * x * x (7 multiplications).

    This difference is trivial for small integers but matters if you put this operation inside a big loop, or if you replace the integers with very large number representations or maybe ginormous matrices.

    Here's one way to get rid of the pow() function without getting rid of the recursion efficiency:

    #include
    #include
    
    int power(int, int);
    
    int main(void)
    {
        int x, n;
        printf("Enter a number and power you wish to raise it to: ");
        scanf_s("%d %d", &x, &n);
        printf("Result: %d\n", power(x, n));
        return 0;
    }
    
    int power(int x, int n)
    {
        int m;
        if (n == 0) return 1;
        if (n % 2 == 0) {
            m = power(x, n / 2);
            return m * m;
        } else return x * power(x, n - 1);
    }
    

提交回复
热议问题