Facebook
From Mariano Moran, 2 Years ago, written in C.
Embed
Download Paste or View Raw
Hits: 234
  1. #include <stdio.h>
  2. #include <cs50.h>
  3. // Global Variables can be invoked by any function
  4. int steps = 0;
  5.  
  6. // Prototypes
  7. int fact(int n);
  8. void collatz (int n);
  9.  
  10. int main(void)
  11. {
  12.         // Fact
  13.     int x = get_int("Fact of ");
  14.     printf("fact of %i equals %i\n", x, fact(x));
  15.    
  16.     // Collatz
  17.     int y = get_int("Collatz of ");
  18.     collatz(y); // counts steps
  19.     printf("Collatz steps of %i: %i\n", y, steps);
  20. }
  21.  
  22. // instead of a for loop
  23. int fact(int n) // works thanks to the execution stack
  24. {
  25.     // base case
  26.     if (n == 1) return 1; // last tab
  27.  
  28.     // recursive case
  29.     else
  30.     {
  31.         return n * fact(n - 1); // close current tab but open a new one
  32.     }
  33. } // in this function you accumulate the closed tabs, for instance, 3 * 2 * 1
  34.  
  35. void collatz (int n) // for counting number of steps
  36. {
  37.     if (n < 1)
  38.     {
  39.         printf("Error: y must be bigger than zero\n");
  40.         return; // error
  41.     }
  42.     if (n == 1) // zero steps
  43.     {
  44.         return; // close tab
  45.     }
  46.     else if (n % 2 == 0) // remainder of n divided by 2
  47.     {
  48.         steps++; // add a step
  49.         collatz(n / 2); // open a simple tab
  50.     }
  51.     else
  52.     {
  53.         steps++; // add a step
  54.         collatz (3 * n + 1); // open an advanced tab
  55.     }
  56.     return; // close simple or advanced tab
  57. }