Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- This file is hereby released to the public domain.
- ~aaaaaa123456789, 2015-01-21
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include "common.h"
- unsigned long long * get_collatz_sequence(unsigned);
- int main (void) {
- printf("Enter a number: ");
- unsigned number = get_number();
- if (!number) {
- fputs("Invalid number entered\n", stderr);
- return 1;
- }
- unsigned long long * seq = get_collatz_sequence(number);
- if (!seq) {
- fputs("Error while calculating sequence: overflowed\n", stderr);
- return 2;
- }
- unsigned long long * curr = seq;
- while (*curr > 1) printf("%llu ", *(curr ++));
- puts("1");
- free(seq);
- return 0;
- }
- unsigned long long * get_collatz_sequence (unsigned number) {
- unsigned long long max_odd = (-1ull) / 3;
- unsigned long long * result = malloc(sizeof(unsigned long long));
- *result = number;
- unsigned count = 0;
- while (result[count] > 1) {
- result = realloc(result, sizeof(unsigned long long) * (count + 2));
- if (!result) return NULL; // yes, this leaks memory, but who cares, the program is aborting anyway
- if (result[count] & 1) {
- if (result[count] > max_odd) return NULL;
- result[count + 1] = (result[count] << 1) + result[count] + 1;
- } else
- result[count + 1] = result[count] >> 1;
- count ++;
- }
- return result;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement