Program to implement Collatz Conjecture - GeeksforGeeks

08 Feb, 2022
Given a positive integer n, the task is to find whether this number reaches to 1 after performing following two 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.
If n is even, then n = n/2.
If n is odd, then n = 3*n + 1.
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++
Java
Python3
C#
Javascript
// 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 codeint main(){    int n = 5;    isToOne(n) ? cout << "Yes" : cout <<"No";    return 0;}
// Java program to implement Collatz Conjectureimport 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 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 Codeif __name__ == "__main__":    n = 5    if isToOne(n):        print("Yes")    else:        print("No") # This code is contributed by# sanjeev2552
// C# program to implement// Collatz Conjectureusing 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
<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 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++
Java
Python 3
C#
Javascript
PHP
// 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 codeint main(){    int n = 5;    isToOne(n) ? cout << "Yes" : cout <<"No";    return 0;}
// Java program to implement Collatz// Conjectureclass 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 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 coden = 5 if isToOne(n) == True:    print("Yes")else:    print("No")     # This code is contributed# by Smitha.
// C# program to implement// Collatz Conjectureusing 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.
<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 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 lengthThis 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. 
Smitha Dinesh Semwal
princiraj1992
Rajput-Ji
sanjeev2552
divyeshrabadiya07
mukesh07
varshagumber28
hazemk537
sumitgumber28
Mathematical
Recursion
Mathematical
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program to find GCD or HCF of two numbers
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find sum of elements in a given array
Program for Tower of Hanoi
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Recursion
Program for Sum of the digits of a given number
Backtracking | Introduction