Advertisement
B1KMusic

9.c

Sep 28th, 2016
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.97 KB | None | 0 0
  1. /* Implementation of the "9" algorithm
  2.  * The algorithm is simple: take any number > 9, and add its digits together, then subtract the sum from the number.
  3.  * Like the Collatz Conjecture, this will always take you to a certain number (in this case: 9).
  4.  */
  5.  
  6. #include <stdio.h>
  7. #include <string.h>
  8. #include <stdlib.h>
  9.  
  10. int
  11. get_sum(int number)
  12. {
  13.     int total = 0;
  14.  
  15.     while(number){
  16.         total += number % 10;
  17.         number /= 10;
  18.     }
  19.  
  20.     return total;
  21. }
  22.  
  23. void
  24. transform_loop(char *initial)
  25. {
  26.     for(int number = atoi(initial); number >= 9; number -= get_sum(number))
  27.         printf("%i  (sum = %i)\n", number, get_sum(number));
  28.  
  29.     printf("0\n----\n");
  30. }
  31.  
  32. void
  33. parse_args(char **argv)
  34. {
  35.     while(*argv)
  36.         transform_loop(*(argv++));
  37. }
  38.  
  39. void
  40. usage()
  41. {
  42.     fputs("Usage: 9 n1 [n2 n3 ...]\n", stderr);
  43.     exit(1);
  44. }
  45.  
  46. int
  47. main(int argc, char **argv)
  48. {
  49.     if(!argv[1])
  50.         usage();
  51.  
  52.     parse_args(argv + 1);
  53.  
  54.     return 0;
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement