Advertisement
aaaaaa123456789

JV programming challenges, season 2, week 1, challenge 1

Jan 20th, 2015
337
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.33 KB | None | 0 0
  1. /*
  2.   This file is hereby released to the public domain.
  3.   ~aaaaaa123456789, 2015-01-21
  4. */
  5.  
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8.  
  9. #include "common.h"
  10.  
  11. unsigned long long * get_collatz_sequence(unsigned);
  12.  
  13. int main (void) {
  14.   printf("Enter a number: ");
  15.   unsigned number = get_number();
  16.   if (!number) {
  17.     fputs("Invalid number entered\n", stderr);
  18.     return 1;
  19.   }
  20.   unsigned long long * seq = get_collatz_sequence(number);
  21.   if (!seq) {
  22.     fputs("Error while calculating sequence: overflowed\n", stderr);
  23.     return 2;
  24.   }
  25.   unsigned long long * curr = seq;
  26.   while (*curr > 1) printf("%llu ", *(curr ++));
  27.   puts("1");
  28.   free(seq);
  29.   return 0;
  30. }
  31.  
  32. unsigned long long * get_collatz_sequence (unsigned number) {
  33.   unsigned long long max_odd = (-1ull) / 3;
  34.   unsigned long long * result = malloc(sizeof(unsigned long long));
  35.   *result = number;
  36.   unsigned count = 0;
  37.   while (result[count] > 1) {
  38.     result = realloc(result, sizeof(unsigned long long) * (count + 2));
  39.     if (!result) return NULL; // yes, this leaks memory, but who cares, the program is aborting anyway
  40.     if (result[count] & 1) {
  41.       if (result[count] > max_odd) return NULL;
  42.       result[count + 1] = (result[count] << 1) + result[count] + 1;
  43.     } else 
  44.       result[count + 1] = result[count] >> 1;
  45.     count ++;
  46.   }
  47.   return result;
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement