How to implement the collatz sequence in C and Python
The collatz sequence is a
- The sequence begins with any positive integer, say
n - If the integer
nis odd, the next number in sequence would be3n+1 - If the integer
nis even, the next number in sequence would ben/2 - The sequence will continue until digit
1is encountered
Example
Let’s understand this with an example.
Assuming that n is 11:
- Since
11is odd, the second number in the sequence is , i.e.,3n=1
Now we have [11, 34,…]
- Since
34is even, the next number is , i.e.,n/2
Now we have [11, 34, 17…]
17is 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.
Algorithm
- Read an integer,
n - If
nis even,n=n/2 - If
nis odd,n=3n+1 - Repeat steps
2and3untilnbecomes1
Code
#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;}