ahmedraza

Collatz code

Nov 18th, 2016
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.66 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <cs50.h>
  3. int coll (int a,int c);
  4. int main (void)
  5. {
  6.     printf("Please enter the int\n");
  7.     //Getting input from user
  8.     int n = GetInt();
  9.     //Used for counting no of iterations
  10.     int count = 0;
  11.     //Calling function
  12.     int ans = coll (n, count);
  13.     //Printing output of function
  14.     printf ("%i\n", ans);
  15. }
  16.  
  17. int coll (int a,int c)
  18. {
  19.     //if a is odd number
  20.     if(a%2==1 && a!=1)
  21.     {
  22.         return coll ((3*a)+1, c+1);
  23.     }
  24.      //If a is even number
  25.     else if(a%2==0 && a!=1)
  26.     {
  27.        return coll (a/2, c+1);
  28.     }
  29.    
  30.     //Base case returns the value of c
  31.    
  32.     else
  33.         return c;
  34. }
Add Comment
Please, Sign In to add comment