Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
c
communitycreator

How to implement the collatz sequence in C and Python

Sai Rohita Bhaskaruni

The collatz sequence is a conjecturespeculation in mathematics that follows a sequence. This sequence is defined below:

  • 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

Example

Let’s understand this with an example.

Assuming that n is 11:

  1. Since 11 is odd, the second number in the sequence is 311+1=343 * 11 + 1 = 34, i.e., 3n=1

Now we have [11, 34,…]

  1. Since 34 is even, the next number is 34/2=1734 / 2 = 17, i.e., n/2

Now we have [11, 34, 17…]

  1. 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.

Algorithm

  1. Read an integer, n
  2. If n is even, n=n/2
  3. If n is odd, n=3n+1
  4. Repeat steps 2 and 3 until n becomes 1

Code

#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