Trusted answers to developer questions

Sai Rohita Bhaskaruni

The **collatz sequence** is a

- The sequence begins with any positive integer, say
`n`

- If the integer
`n`

is odd, the next number in sequence would be`3n+1`

- If the integer
`n`

is even, the next number in sequence would be`n/2`

- The sequence will continue until digit
`1`

is encountered

Let’s understand this with an example.

Assuming that `n`

is `11`

:

- Since
`11`

is odd, the second number in the sequence is $3 * 11 + 1 = 34$, i.e.,`3n=1`

**Now we have [11, 34,…]**

- Since
`34`

is even, the next number is $34 / 2 = 17$, i.e.,`n/2`

**Now we have [11, 34, 17…]**

`17`

is odd, so I suppose you know what to do!

Please note that the sequence continues until digit 1 is encountered. Here is how it goes:

11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1

Now that we know what the Collatz sequence is let’s try coding it.

- Read an integer,
`n`

- If
`n`

is even,`n=n/2`

- If
`n`

is odd,`n=3n+1`

- Repeat steps
`2`

and`3`

until`n`

becomes`1`

#include<stdio.h> int main(){ int n = 11; while(n > 1){ if(n % 2 == 0){ //for even numbers n = n / 2; printf("%d\n", n); } else{ //for odd numbers n = n * 3 + 1; printf("%d\n", n); } } return 0; }

RELATED TAGS

python

c

communitycreator

CONTRIBUTOR

Sai Rohita Bhaskaruni

RELATED COURSES

View all Courses

Keep Exploring

Related Courses