Search code examples
c#functionmathknuth

Evaluating Knuth's arrow notation in a function


I am having trouble calculating Knuth's arrow notation, which is ↑ and can be found here, within a function. What I've made so far is:

int arrowCount = (int)arrowNum.Value; // Part of
BigInteger a = (int)aNum.Value;       // the input I
BigInteger b = (int)bNum.Value;       // already have
BigInteger result = a;
BigInteger temp = a;
for(int i = 0; i < arrowCount; i++)
{
    result = Power(temp, b);
    temp = r;
    b = a;
}

with power being

BigInteger Power(BigInteger Base, BigInteger Pow)
    {
        BigInteger x = Base;
        for(int i = 0; i < (Pow-1); i++)
        {
            x *= Base;
        }
        return x;
    }

but it's incorrect with it's values and I can't figure out a way to fix it. It can handle 1 arrow problems like 3↑3 (which is 3^3 = 9), but it can't handle any more arrows than that.

I need a way to figure out more arrows, such as 3↑↑3,

which should be 7625597484987 (3^27) and I get 19683 (27^3). If you could help me to figure how I could get the proper output and explain what it is I'm doing wrong, I would greatly appreciate it.


Solution

  • I wrote it in java, and use double for input parameter:

        private static double knuthArrowMath(double a, double b, int arrowNum)
    {
        if( arrowNum == 1)
            return Math.pow(a, b);
        double result = a;
        for (int i = 0; i < b - 1; i++)
        {
            result = knuthArrowMath(a, result, arrowNum - 1);
        }
        return result;
    }