#include <stdio.h> #include <stdlib.h> int hailstone(int n, int *arry) { int hs = 1; while (n!=1) { hs++; if (arry) *arry++ = n; n = (n&1) ? (3*n+1) : (n/2); } if (arry) *arry++ = n; return hs; } int main() { int j, hmax = 0; int jatmax, n; int *arry; for (j=1; j<100000; j++) { n = hailstone(j, NULL); if (hmax < n) { hmax = n; jatmax = j; } } n = hailstone(27, NULL); arry = malloc(n*sizeof(int)); n = hailstone(27, arry); printf("[ %d, %d, %d, %d, ...., %d, %d, %d, %d] len=%d\n", arry[0],arry[1],arry[2],arry[3], arry[n-4], arry[n-3], arry[n-2], arry[n-1], n); printf("Max %d at j= %d\n", hmax, jatmax); free(arry); return 0; }
Output:
[ 27, 82, 41, 124, ...., 8, 4, 2, 1] len= 112 Max 351 at j= 7703]With caching:
Much faster if you want to go over a million or so.#include <stdio.h> #define N 10000000 #define CS N /* cache size */ typedef unsigned long ulong; ulong cache[CS] = {0}; ulong hailstone(ulong n) { int x; if (n == 1) return 1; if (n < CS && cache[n]) return cache[n]; x = 1 + hailstone((n & 1) ? 3 * n + 1 : n / 2); if (n < CS) cache[n] = x; return x; } int main() { int i, l, max = 0, mi; for (i = 1; i < N; i++) { if ((l = hailstone(i)) > max) { max = l; mi = i; } } printf("max below %d: %d, length %d\n", N, mi, max); return 0; }
c++#include <iostream> #include <vector> #include <utility> std::vector<int> hailstone(int i) { std::vector<int> v; while(true){ v.push_back(i); if (1 == i) break; i = (i % 2) ? (3 * i + 1) : (i / 2); } return v; } std::pair<int,int> find_longest_hailstone_seq(int n) { std::pair<int, int> maxseq(0, 0); int l; for(int i = 1; i < n; ++i){ l = hailstone(i).size(); if (l > maxseq.second) maxseq = std::make_pair(i, l); } return maxseq; } int main () { // Use the routine to show that the hailstone sequence for the number 27 std::vector<int> h27; h27 = hailstone(27); // has 112 elements int l = h27.size(); std::cout << "length of hailstone(27) is " << l; // starting with 27, 82, 41, 124 and std::cout << " first four elements of hailstone(27) are "; std::cout << h27[0] << " " << h27[1] << " " << h27[2] << " " << h27[3] << std::endl; // ending with 8, 4, 2, 1 std::cout << " last four elements of hailstone(27) are " << h27[l-4] << " " << h27[l-3] << " " << h27[l-2] << " " << h27[l-1] << std::endl; std::pair<int,int> m = find_longest_hailstone_seq(100000); std::cout << "the longest hailstone sequence under 100,000 is " << m.first << " with " << m.second << " elements." <<std::endl; return 0; }
- Output:
length of hailstone(27) is 112 first four elements of hailstone(27) are 27 82 41 124 last four elements of hailstone(27) are 8 4 2 1 the longest hailstone sequence under 100,000 is 77031 with 351 elements.
详见http://rosettacode.org/wiki/Hailstone_sequence#C