Mastering the Ackermann Function

Yesterday I came in touch with a curious, astonishing mathematical function. It’s called Ackermann function.

Mathematically speaking, it is a well-defined total function. That is, it has defined values for every integer input (= total function), and this value is not ambiguous (every input has one and one only possible output value) (= well-defined).

Speaking about computer science, this function is computable, but it’s not a primitive recursive function. In other words, you can implement an algorithm to express the function using while-loops (= computable), but still you cannot write an equivalent algorithm using only do-loops (= not primitive recursive). I suggest you to try this statement.

The function has this form:

As you can see, it’s form is fairly simple. But, even if it seems simple, its values explode quickly. A(4, 2), for example, has more than 19.000 digits.

Ackermann Function on the complex plane

Representation of the Ackermann Function on the complex plane

What I want to talk about is the possible implementation of such a function by means of a computer algorithm. I will use Python for the next examples, but the description is language-independent.

Recursive approach

The quicker approach to solving such a problem is by implementing a recursive algorithm, since the definition of the function itself is recursive. Let’s try with something like this:

import sys

def A(x, y):
  if x == 0:
    return y+1
  else:
    if y == 0:
      return A(x-1, 1)
    else:
      return A(x-1, A(x, y-1))

x = int(sys.argv[1])
y = int(sys.argv[2])

print "Result of A(%d, %d) is %d" % (x, y, A(x, y))

You will want to try it calling from command line:

python ackermann.py 4 2

You will face a brutal reality: this algorithm will not end for the input (4, 2), since it quickly reaches the maximum recursion depth provided by Python. We will get better results starting from lower inputs.

You will find that the maximum computable values, for each possible x are:

  • A(1, 997) = 999
  • A(2, 497) = 997
  • A(3, 6) = 509
  • A(4, 0) = 13

For every input (x, y) with x greater than 5 you will get no result, for each y. As you can see, the function quickly diverges in complexity when x = 3, and much more when x = 4.

What we can try to do is jump as much iterations as possible with a simple trick: saving already computed values in order to not compute them anymore. This could simplify the navigation through the recursion graph.

Let’s try this implementation (with some debug information):

import sys

res = {}
jumps = 0
recursions = 0

#------ Start Method -------#
def A(x, y):
  global res, jumps, recursions

  recursions += 1
  try:
    jumps += 1
    return res[x][y]
  except Exception, e:
    jumps -= 1
    res[x] = {}

  if x == 0:
    res[x][y] = y+1
  else:
    if y == 0:
      res[x][y] = A(x-1, 1)
    else:
      res[x][y] = A(x-1, A(x, y-1))

  return res[x][y]
#------ End Method -------#

x = int(sys.argv[1])
y = int(sys.argv[2])

try:
  print "Result of A(%d, %d) is %d" % (x, y, A(x, y))
  print "%d total recursions, %d operations avoided" % (recursions, jumps)
except Exception, e:
  print "Exception occurred after %d recursions" % (recursions)

As you can see, the res variable is loaded with each computed value (at lines 20, 23, 25), and at the beginning of the function we try to return the value of A(x, y) if already computed (at line 14). The jumps variable keeps track of the number of the iterations saved by this implementation, while the recursions variable keeps track of the total number of single calls the the A function.

You can now still try to call the function to see what the maximum computable values are. You will find this:

  • A(1, 995) = 997
  • A(2, 496) = 995
  • A(3, 6) = 509
  • A(4, 0) = 13

We got three results: the maximum computable inputs have decreased ((1, 995) instead of (1,997) for example), the number of jumps increases with increasing values of the inputs, thus the computation time has decreased. Sadly, our target was not to reduce computable time, but reduce recursion depth.

We should try something different, to truly master the Ackermann Function. This something different involves computing the analytic form of the function. This approach will show a completely different world.

Probably I’ll talk about that in a future article. Let me know what you think about it, and submit your different implementations (different languages, different approaches) but still focusing on the recursion optimization.

30.018 thoughts on “Mastering the Ackermann Function

  1. Magnificent site. Lots of helpful information here.
    I’m sending it to several buddies ans additionally sharing in delicious.

    And of course, thank you on your sweat!

  2. I ɑm tһe office manager ߋf Eastern Ray Shisha (easternrayshisha.сo.uk), a
    deluxe luxury shisha hire harrow weddings birthday parties middle eastern themed events corporate events and house parties hire firm.
    Ꮤe’re at this time organizing а gigantic wedding and reception jjst ߋutside Lodon and
    I am searchbing dependable Belly Dancers Hire
    І was spedulating if anybߋdy att marzapower.сom can assist me.
    Does anyone happen to have some local contacts?
    The client іs hqppy to hire personnel from abroad ɑs top quality iss tһe
    central poіnt tߋ ⅽonsider. Money is not ɑn issue.
    Tһanks іn advance.

  3. I truly love your website.. Very nice colors & theme.
    Did you create this amazing site yourself? Please reply back as
    I’m hoping to create my own personal site and would love
    to know where you got this from or exactly what the
    theme is named. Many thanks!

  4. You could certainly see your expertise within the work you write.
    The sector hopes for more passionate writers like you who aren’t afraid to say how they believe.
    Always go after your heart.

  5. Thank you for some other informative site.

    The place else may I get that type of information written in such an ideal way?
    I have a project that I’m just now operating on, and I have been at the look out for
    such information.

  6. Hey! Quick question that’s totally off topic. Do you know how to make your
    site mobile friendly? My website looks weird when viewing from
    my iphone4. I’m trying to find a theme or plugin that might be able to resolve this
    problem. If you have any recommendations, please share.
    Thanks!

  7. Howdy! This post couldn’t be written any better! Reading this
    post reminds me of my good old room mate! He always kept talking about this.
    I will forward this post to him. Pretty sure he will have
    a good read. Many thanks for sharing!

  8. Hi everybody аt marzapower.com! I am the owner of StarLightBreeze.ⅽom Guided Meditations Online Site.
    Ι want to share mʏ totally free relaxatiokn audio lectures ѕuch as Guided Daytime Meditation Meditation fοr Focys annd Productivity
    аnd Guided Meditstion for Couples witһ everʏbody аt marzapower.сom tο heⅼр you to handle tension as well ass unwind.
    Much Love xox

  9. Postingan yang baik sekali. Saya menyukainya. Setiap manusia tentu berkeinginan mempunyai rumah
    yang bagus dan nyaman. Tetapi, untuk memilih model & desain hunian yang pas dengan selera akan menjadi sulit jika tidak mempunyai sampel bentuknya.

    Dari sini kita akan memaparkan gambaran mengenai model
    rumah minimalis terkini. Karena selain nyaman, model terbaru akan pas
    untuk anda yang ikut perkembangan zaman. rumah wonosari

  10. hello there and thank yoou for your info – I’ve certainly picked
    upp anything new from rkght here. I diid howevr expertise
    several technical issues using this site, as I experienced
    to reload the web site many times previous to
    I coulod get it to lokad properly. I had been wondering if your
    hosting is OK? Not that I’m complaining, but slow lading instances times will very frequently affect your placement
    in google and could damage your quality score
    if advertising and marketing wit Adwords. Anyway I’m adding ths RSS to my e-mail and could look out for a lot more of your respective fascinatinng content.
    Ensure that you update this again very soon.
    webpage

  11. I’m not sure exactly why but this site is loading
    very slow for me. Is anyone else having this problem or is it a
    problem on my end? I’ll check back later on and see if the
    problem still exists.

  12. Hey this is kind of of off topic but I was wanting to know if blogs use WYSIWYG editors or if you have
    to manually code with HTML. I’m starting a blog soon but have no coding experience so I wanted to get guidance from someone with experience.
    Any help would be greatly appreciated!

  13. I’m not sure where you’re getting your info, but great topic.

    I needs to spend some time learning much more or understanding more.

    Thanks for fantastic information I was looking for this
    information for my mission.

  14. Hey there! I understand this is sort of off-topic however I had to ask.
    Does running a well-established blog such as yours require a lot
    of work? I’m completely new to writing a blog however I do write
    in my journal every day. I’d like to start a blog so I can share my own experience and feelings online.

    Please let me know if you have any kind of recommendations or tips for new
    aspiring blog owners. Thankyou!

  15. Postingan yang baik sekali. Saya menyukainya.

    Setiap orang tentu berkeinginan mempunyai hunian yang bagus dan nyaman. Tetapi, untuk menentukan model & desain hunian yang tepat dengan selera akan menjadi susah
    jika tidak mempunyai sampel bentuknya. Dari sini kita akan menguraikan gambaran mengenai model rumah minimalis terkini.
    Karena selain keren, model terkini akan tepat untuk anda yang ikut perkembangan zaman. agensi properti

  16. Please let me know if you’re looking for a article writer for your weblog.
    You have some really great articles and I think I would be a good asset.
    If you ever want to take some of the load off, I’d really like to write some material
    for your blog in exchange for a link back to mine. Please shoot me an email if interested.
    Cheers!

  17. Can I just say what a comfort to find somebody that actually understands what they’re talking about on the net.
    You actually know how to bring a problem to light and make
    it important. A lot more people must read this and understand this side
    of your story. I was surprised you are not more popular since you surely possess the
    gift.

    Here is my blog post; agency start-up

  18. As news of Hunter Biden’s fondness for strip clubs continues to unfold, revelations came out on Wednesday that
    not only did he impregnate a DC stripper, he also had sex toys
    used on him by dancers at the Hustler Club in New York City.

  19. Hello there, I think your blog may be having internet browser compatibility problems.
    When I look at your blog in Safari, it looks fine however,
    when opening in IE, it’s got some overlapping issues.
    I simply wanted to provide you with a quick heads up! Apart
    from that, fantastic blog!

  20. Wow, amazing blog layout! How long have you been blogging for?
    you make blogging look easy. The overall look of your
    website is wonderful, let alone the content!

  21. Thank you a lot for sharing this with all folks you actually realize what you
    are talking approximately! Bookmarked. Please also visit my web site
    =). We may have a hyperlink trade contract between us

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *