Algorithms_in_C 1.0.0
Set of algorithms implemented in C.
Loading...
Searching...
No Matches
collatz.c File Reference

Implementation of Collatz' conjecture More...

#include <stdio.h>
#include <stdlib.h>
Include dependency graph for collatz.c:

Functions

int main (int argc, char *argv[])
 Main function.
 

Detailed Description

Implementation of Collatz' conjecture

Collatz conjecture: a series for a number \(n\) in which if \(n\) even then the next number is \(\frac{n}{2}\) ,but if n is odd then the next number is \(3n+1\). This series continues till \(n\) reaches 1

Function Documentation

◆ main()

int main ( int  argc,
char *  argv[] 
)

Main function.

17{
18 unsigned long long n, curr_no, num_steps = 0;
19 if (argc == 2)
20 n = strtoull(argv[1], NULL, 10);
21 else
22 {
23 printf("Enter starting number: ");
24 scanf("%lu", &n); // input number
25 }
26
27 curr_no = n; // curr_no stores input number n
28 while (curr_no != 1) // loop till series reaches 1
29 {
30 num_steps++;
31 printf("%llu->", curr_no);
32 if (curr_no % 2 == 0) // condition for even number
33 curr_no = curr_no / 2;
34 else
35 curr_no = (curr_no * 3) + 1; // condition for odd number
36 }
37 printf("1\nNumber of steps: %llu\n", num_steps);
38 return 0;
39}