[ create a new paste ] login | about

Link: http://codepad.org/Hten1l7U    [ raw code | fork ]

C++, pasted on Feb 15:
// You can memoize:

struct Memo3n1 {
  std::map<int, int> lengths;

  Memo3n1() {
    lengths[1] = 1;
  }

  int cycle_length(int number) {
    assert(number >= 1);
    std::map<int, int>::iterator x = lengths.find(x);
    if (x == lengths.end()) {
      int next = ((n % 2 == 0) ? n / 2 : 3 * n + 1);
      int length = 1 + cycle_length(next);
      x = lengths.insert(std::make_pair(number, length)).first;
    }
    return x->second;
  }

  int max_cycle_length(int begin, int end) {
    assert(begin <= end);
    int x = begin;
    int max = cycle_length(x);
    while (++x <= end) {
      max = std::max(max, cycle_length(x));
    }
    return max;
  }
};


Create a new paste based on this one


Comments: