int main(void) { assert(collatz_length(1) == 1); assert(collatz_length(2) == 2); assert(collatz_length(13) == 10); print_longest_sequence(1, 1); print_longest_sequence(1, 10); print_longest_sequence(1, 1000); print_longest_sequence(1, 1000000); return 0; }
uint64_t collatz_length(uint64_t n, uint64_t* memo) { uint64_t next = n % 2 ? 3 * n + 1 : n / 2; if (n <= SIZE) { if (! memo[n]) memo[n] = 1 + collatz_length(next, memo); return memo[n]; } else return 1 + collatz_length(next, memo); }
int main(){ unsigned limit = 1000000; unsigned* cache = calloc(limit, sizeof(unsigned)); cache[1] = 1; assert(collatz_length(13, cache, limit) == 10); printf("%u\n", max_collatz_chain(limit, cache)); return 0; }
int collatz_length(unsigned long long num) { if ((num < max_num) && collatz_array[num] != 0) { return collatz_array[num]; } else if (num == 1) { return 1; } else { unsigned long long new_num = collatz_next(num); return 1 + collatz_length(new_num); } }
unsigned int max_collatz_chain(unsigned limit, unsigned* cache){ unsigned max_length = 0; unsigned length; unsigned owner = 0; for (unsigned i = 1; i < limit; i++){ length = collatz_length(i, cache, limit); if (length > max_length){ owner = i; max_length = length; } } return owner; }
int64_t collatz_length(const int64_t number, std::map<int64_t, int64_t>& collatz_sequence) { if (number == 1) { return 1; } if (collatz_sequence.find(number) == collatz_sequence.end()) { collatz_sequence[number] = collatz_length((number%2 == 0) ? number/2 : number*3+1, collatz_sequence) + 1; } return collatz_sequence[number]; }
static sequence_info_t find_longest_sequence(integer min, integer max) { sequence_info_t result = {}; for (; min <= max; ++min) { size_t const length = collatz_length(min); if (length > result.length) { result.length = length; result.start = min; } } return result; }
inline uint64_t f() { uint64_t *memo = (uint64_t *)calloc(SIZE + 1, sizeof(uint64_t)); uint64_t ans, i, max = 0; memo[1] = 1; for (i = 1; i <= SIZE; i++) { uint64_t tmp = collatz_length(i, memo); if (tmp > max) { max = tmp; ans = i; } } free(memo); return ans; }
int main(void) { std::map<int64_t, int64_t> collatz_sequence; auto max_length = 0LL; auto max_i = 0LL; for (auto i = 1; i < 1000000; i++) { auto length = collatz_length(i, collatz_sequence); if (length > max_length) { max_length = length; max_i = i; } } std::cout << "answer: " << max_i << "\n"; return 0; }
void generate_collatz_array() { for (int i = 1; i < max_num; i++) { int length = collatz_length(i); collatz_array[i] = length; } }