3N+1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | int threeN(int n) { if (n%2==0) return n/2; else return n*3+1; } int getLength(int n) { static map<int, int> history; int key = n; if (n == 1) return 1; if (history.find(key) != history.end()) return history[key]; int length = getLength(threeN(n))+1; history[key] = length; return length; } |
分类: C&&C++, Programming
近期评论