ackermann.html
001| '''Ackermann Function. Insane busy work; blows up stack easily!
001|
001| /* Ackermann Function.
001| * From Computerphile YouTube channel.
001| * http://www.eprg.org/computerphile/ackermann.c
001| */
001| #include <stdio.h>
001|
001| int ackermann (int m,int n)
001| {
001| /* If the first argument is zero... */
001| if (m == 0)
001| /* Return the second argument+1... */
001| return n+1;
001|
001| /* If the second argument is zero... */
001| if (n == 0)
001| /* Return recursion of the second argument+1 PLUS the first argument-1... */
001| return ackermann(m-1, 1);
001|
001| /* Otherwise return recursed recursion (!!)... */
001| return ackermann(m-1, ackermann(m,n-1));
001| }
001|
001| int main (int argc, char* argv[])
001| {
001| for (int i=0; i<6; i++)
001| {
001| for (int j=0; j<6; j++)
001| {
001| printf("ackerman (%d,%d) is: %d\n",i,j, ackermann(i,j));
001| }
001| }
001| return 0;
001| }
001|
001| '''
002|
003| from sys import stdout
004| from os import path
005|
006| BasePath = r'C:\CJS\prj\Python\@sandbox'
007|
008|
009|
010| def ackermann (m, n, fp=stdout, level=1):
011|
012| if m == 0:
013| print('[%05d]0,%d: return(%d)' % (level,m,n+1), file=fp)
014| return n+1
015|
016| if n == 0:
017| print('[%05d]%d,0: ackermann(%d,1)' % (level,m,m-1), file=fp)
018| return ackermann(m-1, 1, fp, level+1)
019|
020| print('[%05d]%d,%d: ackermann(%d, ackermann(%d,%d))' % (level,m,n,m-1,m,n-1), file=fp)
021| return ackermann(m-1, ackermann(m,n-1,fp,level+1), fp, level+1)
022|
023|
024|
025| def test_ackermann (m, n, fp=stdout):
026| for mx in range(m):
027| print('[M] %d' % mx, file=fp)
028| for nx in range(n):
029| print('[M][N] %d-%d' % (mx,nx), file=fp)
030| print('Ackermann(%d,%d):' % (mx,nx), file=fp)
031| result = ackermann(mx,nx, fp)
032| print('Ackermann(%d,%d) = %d' % (mx,nx, result), file=fp)
033| print(file=fp)
034| print(file=fp)
035| print(file=fp)
036|
037|
038|
039| fn = path.join(BasePath, 'ackermann.out')
040| fp = open(fn, mode='w', encoding='utf-8')
041| try:
042| test_ackermann(3, 9, fp)
043|
044|
045|
046|
047| except:
048| raise
049| finally:
050| fp.close()
051|
052|
053|
054|
055| '''eof'''
056|