Program to implement Collatz Conjecture

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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right



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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Python 3

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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
?>

chevron_right



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 contribute.geeksforgeeks.org or mail your article to contribute@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.



My Personal Notes arrow_drop_up



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.