Program to print Collatz Sequence
Last Updated :
22 Jun, 2022
Starting with any positive integer N, Collatz sequence is defined corresponding to n as the numbers formed by the following operations :
- If n is even, then n = n / 2.
- If n is odd, then n = 3*n + 1.
- Repeat above steps, until it becomes 1.
Examples :
Input : 3
Output : 3, 10, 5, 16, 8, 4, 2, 1
Input : 6
Output : 6, 3, 10, 5, 16, 8, 4, 2, 1
Below is the implementation :
C++
#include <bits/stdc++.h>
using namespace std;
void printCollatz( int n)
{
while (n != 1)
{
cout << n << " " ;
if (n & 1)
n = 3*n + 1;
else
n = n/2;
}
cout << n;
}
int main()
{
printCollatz(6);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static void printCollatz( int n)
{
while (n != 1 )
{
System.out.print(n + " " );
if ((n & 1 ) == 1 )
n = 3 * n + 1 ;
else
n = n / 2 ;
}
System.out.print(n);
}
public static void main (String[] args)
{
printCollatz( 6 );
}
}
|
Python3
def printCollatz(n):
while n ! = 1 :
print (n, end = ' ' )
if n & 1 :
n = 3 * n + 1
else :
n = n / / 2
print (n)
printCollatz( 6 )
|
C#
using System;
class GFG {
static void printCollatz( int n)
{
while (n != 1)
{
Console.Write (n + " " );
if ((n & 1) == 1)
n = 3 * n + 1;
else
n = n / 2;
}
Console.Write (n);
}
static void Main()
{
printCollatz(6);
}
}
|
PHP
<?php
function printCollatz( $n )
{
while ( $n != 1)
{
echo $n . " " ;
if ( $n & 1)
$n = 3 * $n + 1;
else
$n = $n / 2;
}
echo $n ;
}
printCollatz(6);
?>
|
Javascript
<script>
function printCollatz(n)
{
while (n != 1)
{
document.write(n + " " );
if ((n & 1) != 0)
n = 3*n + 1;
else
n = parseInt(n/2, 10);
}
document.write(n);
}
printCollatz(6);
</script>
|
Output
6 3 10 5 16 8 4 2 1
Time Complexity: O(log n) since n is halved in while loop
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...