Recursive powerof-function, see if you can solve it

Posted by Jonas B on Stack Overflow See other posts from Stack Overflow or by Jonas B
Published on 2010-04-23T23:25:06Z Indexed on 2010/04/23 23:43 UTC
Read the original article Hit count: 214

Filed under:

First of all, this is not schoolwork - just my curiousity as I for some reason can't get my head around it and solve it. I come up with these stupid things all the time and it annoys the hell out of me when I cant solve them.

Code example is in C# but solution doesn't have to be in any particular programming-language.

long powerofnum(short num, long powerof)
    {
        return powerofnum2(num, powerof, powerof);
    }

    long powerofnum2(short num, long powerof, long holder)
    {
        if (num == 1)
            return powerof;
        else
        {
            return powerof = powerofnum2(num - 1, holder * powerof, holder);
        }
    }

As you can see I have two methods. I call for powerofnum(value, powerofvalue) which then calls the next method with the powerofvalue also in a third parameter as a placeholder so it remembers the original powerof value through the recursion.

What I want to accomplish is to do this with only one method. I know I could just declare a variable in the first method with the powerof value to remember it and then iterate from 0 to value of num. But as this is a theoretical question I want it done recursively.

I could also in the first method just take a third parameter called whatever to store the value just like I do in the second method that is called by the first, but that looks really stupid. Why should you have to write what seems like the same parameter twice?

Rules explained in short:

  • no iteration
  • scope-specific variables only
  • only one method

Anyhow, I'd appreciate a clean solution.

Good luck :)

© Stack Overflow or respective owner

Related posts about recursion