Skip to content
Related Articles

Related Articles

Improve Article

Program to implement Collatz Conjecture

  • Difficulty Level : Easy
  • Last Updated : 07 Jul, 2021

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

  1. If n is even, then n = n/2.
  2. If n is odd, then n = 3*n + 1.
  3. Repeat 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 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;
  
    // 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




// Jav 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


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 reaches to 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.

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

We strongly recommend to refer below problem as an exercise:

Maximum Collatz sequence length

This article is contributed by Sahil Chhabra (akku). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :