Open In App

Program to implement Collatz Conjecture

Last Updated : 07 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a positive integer n, the task is to find whether this number reaches 1 after performing the following two operations:- 

  1. If n is even, then n = n/2.
  2. If n is odd, then n = 3*n + 1.
  3. Repeat the above steps, until it becomes 1.

For example, for n = 12, we get the sequence 12, 6, 3, 10, 5, 16, 8, 4, 2, 1.

Examples: 

Input : n = 4
Output : Yes
Input : n = 5
Output : Yes

The idea is to simply follow given rules and recursively call the function with reduced values until it reaches 1. If a value is seen again during recursion, then there is a cycle and we can't reach 1. In this case, we return false. 

C++
// C++ program to implement Collatz Conjecture
#include<bits/stdc++.h>
using namespace std;

// Function to find if n reaches to 1 or not.
bool isToOneRec(int n, unordered_set<int> &s)
{
    if (n == 1)
        return true;

    // If there is a cycle formed, we can't r
    // reach 1.
    if (s.find(n) != s.end())
        return false;
     s.insert(n);//inserting elements to the s

    // If n is odd then pass n = 3n+1 else n = n/2
    return (n % 2)? isToOneRec(3*n + 1, s) :
                    isToOneRec(n/2, s);
}

// Wrapper over isToOneRec()
bool isToOne(int n)
{
   // To store numbers visited using recursive calls.
   unordered_set<int> s;

   return isToOneRec(n, s);
}

// Drivers code
int main()
{
    int n = 5;
    isToOne(n) ? cout << "Yes" : cout <<"No";
    return 0;
}
Java
// Java program to implement Collatz Conjecture
import java.util.*;

class GFG 
{

    // Function to find if n reaches to 1 or not.
    static boolean isToOneRec(int n, HashSet<Integer> s) 
    {
        if (n == 1) 
        {
            return true;
        }

        // If there is a cycle formed, we can't r
        // reach 1.
        if (s.contains(n)) 
        {
            return false;
        }

        // If n is odd then pass n = 3n+1 else n = n/2
        return (n % 2 == 1) ? isToOneRec(3 * n + 1, s)
                : isToOneRec(n / 2, s);
    }

    // Wrapper over isToOneRec()
    static boolean isToOne(int n) 
    {
        // To store numbers visited using recursive calls.
        HashSet<Integer> s = new HashSet<Integer>();

        return isToOneRec(n, s);
    }

    // Drivers code
    public static void main(String[] args) 
    {
        int n = 5;
        if (isToOne(n)) 
        {
            System.out.print("Yes");
        } 
        else 
        {
            System.out.print("No");
        }
    }
}

/* This code contributed by PrinciRaj1992 */
Python3
# Python3 program to implement Collatz Conjecture

# Function to find if n reaches to 1 or not.
def isToOneRec(n: int, s: set) -> bool:
    if n == 1:
        return True

    # If there is a cycle formed,
    # we can't reach 1.
    if n in s:
        return False

    # If n is odd then pass n = 3n+1 else n = n/2
    if n % 2:
        return isToOneRec(3 * n + 1, s)
    else:
        return isToOneRec(n // 2, s)

# Wrapper over isToOneRec()
def isToOne(n: int) -> bool:

    # To store numbers visited
    # using recursive calls.
    s = set()

    return isToOneRec(n, s)

# Driver Code
if __name__ == "__main__":
    n = 5
    if isToOne(n):
        print("Yes")
    else:
        print("No")

# This code is contributed by
# sanjeev2552
C#
// C# program to implement 
// Collatz Conjecture
using System; 
using System.Collections.Generic; 
    
class GFG 
{

    // Function to find if n reaches to 1 or not.
    static Boolean isToOneRec(int n, HashSet<int> s) 
    {
        if (n == 1) 
        {
            return true;
        }

        // If there is a cycle formed, 
        // we can't reach 1.
        if (s.Contains(n)) 
        {
            return false;
        }

        // If n is odd then pass n = 3n+1 else n = n/2
        return (n % 2 == 1) ? isToOneRec(3 * n + 1, s)
                            : isToOneRec(n / 2, s);
    }

    // Wrapper over isToOneRec()
    static Boolean isToOne(int n) 
    {
        // To store numbers visited using 
        // recursive calls.
        HashSet<int> s = new HashSet<int>();

        return isToOneRec(n, s);
    }

    // Driver code
    public static void Main(String[] args) 
    {
        int n = 5;
        if (isToOne(n)) 
        {
            Console.Write("Yes");
        } 
        else
        {
            Console.Write("No");
        }
    }
}

// This code contributed by Rajput-Ji
JavaScript
<script>
    // Javascript program to implement Collatz Conjecture
    
    // Function to find if n reaches to 1 or not.
    function isToOneRec(n, s) 
    {
        if (n == 1) 
        {
            return true;
        }
  
        // If there is a cycle formed, 
        // we can't reach 1.
        if (s.has(n)) 
        {
            return false;
        }
  
        // If n is odd then pass n = 3n+1 else n = n/2
        return (n % 2 == 1) ? isToOneRec(3 * n + 1, s)
                            : isToOneRec(n / 2, s);
    }
  
    // Wrapper over isToOneRec()
    function isToOne(n) 
    {
        // To store numbers visited using 
        // recursive calls.
        let s = new Set();
  
        return isToOneRec(n, s);
    }
    
    let n = 5;
    if (isToOne(n)) 
    {
      document.write("Yes");
    } 
    else
    {
      document.write("No");
    }
    
    // This code is contributed by divyeshrabadiya07.
</script>

Output
Yes

The above program is inefficient. The idea is to use Collatz Conjecture. It states that if n is a positive then somehow it will reach 1 after a certain amount of time. So, by using this fact it can be done in O(1) i.e. just check if n is a positive integer or not. 
Note that the answer would be false for negative numbers. For negative numbers, the above operations would keep number negative and it would never reach 1.

C++
// C++ program to implement Collatz Conjecture
#include<bits/stdc++.h>
using namespace std;

// Function to find if n reaches to 1 or not.
bool isToOne(int n)
{
    // Return true if n is positive
    return (n > 0);
}

// Drivers code
int main()
{
    int n = 5;
    isToOne(n) ? cout << "Yes" : cout <<"No";
    return 0;
}
Java
// Java program to implement Collatz
// Conjecture
class GFG {
    
    // Function to find if n reaches
    // to 1 or not.
    static boolean isToOne(int n)
    {
        
        // Return true if n is positive
        return (n > 0);
    }
    
    // Drivers code
    public static void main(String[] args)
    {
        int n = 5;
        
        if(isToOne(n) == true)
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}

// This code is contributed by Smitha.
Python 3
# Python 3 program to implement
# Collatz Conjecture

# Function to find if n 
# reaches to 1 or not.
def isToOne(n):

    # Return true if n
    # is positive
    return (n > 0)

# Drivers code
n = 5

if isToOne(n) == True:
    print("Yes")
else:
    print("No")
    
# This code is contributed
# by Smitha.
C#
// C# program to implement
// Collatz Conjecture
using System;

class GFG {
    
    // Function to find if n
    // reaches to 1 or not.
    static bool isToOne(int n)
    {
        
        // Return true if n 
        // is positive
        return (n > 0);
    }
    
    // Drivers code
    public static void Main()
    {
        int n = 5;
        
        if(isToOne(n) == true)
            Console.Write("Yes") ;
        else
            Console.Write("No");
    }
}

// This code is contributed
// by Smitha.
JavaScript
<script>
    // Javascript program to implement Collatz Conjecture
    
    // Function to find if n
    // reaches to 1 or not.
    function isToOne(n)
    {
         
        // Return true if n
        // is positive
        return (n > 0);
    }
    
    let n = 5;
         
    if(isToOne(n) == true)
      document.write("Yes") ;
    else
      document.write("No");
    
    // This code is contributed by mukesh07.
</script>
PHP
<?php
// PHP program to implement Collatz Conjecture

// Function to find if n reaches
// to 1 or not.
function isToOne($n)
{
    // Return true if n is positive
    if($n > 0)
        return true;
    return false;
}

// Driver code
$n = 5;
isToOne($n)? print("Yes") : print("No");

// This code is contributed by princiraj1992
?>

Output
Yes

Time complexity: O(1)
Auxiliary space: O(1)


We strongly recommend to refer below problem as an exercise: 
Maximum Collatz sequence length


 


Next Article
Article Tags :
Practice Tags :

Similar Reads