I wrote the "Ackerman" function in Visual Studio. Stack Overflow occured very quickly

549 Views Asked by At

I was watching this video - https://youtu.be/i7sm9dzFtEI on youtube, and decided it would be fun to copy that function in C#

Well I ran it, and it stopped after 21 calls and around one second. The guy's program on the video has apparently been running for about 4 weeks and is still running.

static int ack(int m, int n)
{
    int answer;
    if (m == 0) answer = n + 1;
    else if (n == 0) answer = ack(m - 1, 1);
    else answer = ack(m - 1, ack(m, n - 1));
    return answer;
}
static void Main(string[] args)
{
    for (int i = 0; i < 6; i++)
        for (int j = 0; j < 6; j++)
            Console.WriteLine($"ackerman ({i},{j}) is:{ack(i, j)}");
    Console.ReadLine();
}

Is there something I can do to make mine run for longer?

Edit: I changed from 'Debug' to 'Release' and got one more iteration and a few more seconds.

1

There are 1 best solutions below

0
On

Keep a track of already calculated values for the given parameters and return the cached value instead of calculating it again and again.