Using Recursion to raise a base to its exponent - C++

后端 未结 5 668
不知归路
不知归路 2020-12-22 10:42

I simply want to write some code that makes use of recursion of functions to raise a base to its power. I know that recursion is not the most right way to do things in C++,

5条回答
  •  离开以前
    2020-12-22 11:08

    To make this an actual C++ answer – this is the kind of task where you might consider making it a template function, as this should work with any kind of number type.

    Recursion is in fact a good idea, but only if you make use of the benefits it can offer: it can avoid some of the multiplications, by factoring out low numbers from the exponent.

    template 
    NumT raiseTo(NumT base, unsigned exponent) {
      if (exponent == 1) return base;
      if (exponent == 0) return 1;
      if (exponent%2 == 0) { NumT ressqrt = raiseTo(base,exponent/2)
                           ; return ressqrt*ressqrt;                  }
      if (exponent%3 == 0) { NumT rescubrt = raiseTo(base,exponent/3)
                           ; return rescubrt*rescubrt*rescubrt;       }
      else return base * raiseTo(base, --exponent);
    }
    

    An example how many calculation this can save: suppose you want to raise a number to 19. That's 18 multiplications if you use the naïve loop-like approach. With this solution, what happens is

    • 19 isn't divisible by either 2 or 3, so calculate bbe-1, which is
    • b18. Now 18 is divisible by 2, so we square be/2, which is
    • b9. Where 9 is divisible by 3, so we cube be/3, which is
    • b3. Where 3 is divisible by 3, so we cube be/3, which is
    • b1, which is b.

    That was only 1+1+2+2 = 6 multiplications, 1/3 of the necessary amount for the loop-like approach! However, note that this doesn't necessarily mean the code will execute much faster, as the checking of factors also takes some time. In particular, the %3 on unsigneds is probably not faster than multiplication on ints, so for NumT==int it's not really clever at all. But it is clever for the more expensive floating point types, complex, not to speak of linear algebra matrix types for which multiplication may be extremely expensive.

提交回复
热议问题