The collatz sequence is a
n
n
is odd, the next number in sequence would be 3n+1
n
is even, the next number in sequence would be n/2
1
is encounteredLet’s understand this with an example.
Assuming that n
is 11
:
11
is odd, the second number in the sequence is , i.e., 3n=1
Now we have [11, 34,…]
34
is even, the next number is , 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.
n
n
is even, n=n/2
n
is odd, n=3n+1
2
and 3
until n
becomes 1
#include<stdio.h>int main(){int n = 11;while(n > 1){if(n % 2 == 0){ //for even numbersn = n / 2;printf("%d\n", n);}else{ //for odd numbersn = n * 3 + 1;printf("%d\n", n);}}return 0;}