Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Efficient Ackermann function

Name: Anonymous 2007-06-03 6:31 ID:dAfZE6X7

Ackermann is a complex recursive function (I still don't know how this differs from a simple recursive function) that grows really really freaking quickly.

I've implemented a very quick method of calculating the results. It's faster because I noticed a great deal of duplicate function calls, so I put known values into a table & look them up when the values match up.

However, it segfaults for n, m > 4, 1 or 3 14. I was wondering if there's a way to fix this. Obviously I'm running out of memory (can't attach pic here, but valgrind says can't grow the stack) :)

Excuse the shitty code, I'm still learning C++. I know that I should probably have a set of pairs of ints rather than using that stringstream conversion BS. Feel free to suggest some ways to help efficiency =D

Thanks,
Anon.

#include <iostream>
#include <map>
#include <stdlib.h>
#include <stdio.h>
#include <sstream>

using namespace std;

map<string,int> cache;

int ack(int m, int n) {
  string key;
  stringstream ss;
  ss << m << "," << n;
  ss >> key;
  if (cache.find(key) != cache.end()) {
    return(cache[key]);
  }

  int result;
  if (m == 0) {
    cache[key] = n+1;
    return n+1;
  }
  else if (n == 0) {
    result = ack(m-1, 1);
    cache[key] = result;
    return result;
  }
  else {
    result = ack(m-1, ack(m, n-1));
    cache[key] = result;
    return result;
  }
}

int main() {
  int a, b;
  cout << "Enter a and b, ( <0 || <0 ) to quit \n";
  cin >> a >> b;
  while (a > 0 && b > 0) {
    cout << "Ack is: " << ack(a, b) << endl;
    cin >> a >> b;
  }
}

Name: Anonymous 2007-06-03 12:38 ID:O6de21s0

>>1
you should probably use a pair of ints rather than using that stringstream conversion BS.  or just create a 2d lookup table and get rid of most of your overhead.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List