📜  实施Collatz猜想的程序

📅  最后修改于: 2021-04-23 20:16:14             🧑  作者: Mango

给定正整数n,任务是在执行以下两项操作后查找该数字是否达到1:

  1. 如果n为偶数,则n = n / 2。
  2. 如果n为奇数,则n = 3 * n + 1。
  3. 重复上述步骤,直到变为1。

例如,对于n = 12,我们得到序列12、6、3、10、5、16、8、4、2、1。

例子:

Input : n = 4
Output : Yes

Input : n = 5
Output : Yes

想法是简单地遵循给定的规则,并递归地调用具有减小值的函数,直到达到1。如果在递归过程中再次看到某个值,则存在一个循环,而我们无法达到1。在这种情况下,我们返回false。

C++
// C++ program to implement Collatz Conjecture
#include
using namespace std;
  
// Function to find if n reaches to 1 or not.
bool isToOneRec(int n, unordered_set &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 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 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 s = new HashSet();
  
        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 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 s = new HashSet();
  
        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


C++
// C++ program to implement Collatz Conjecture
#include
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
 0)
        return true;
    return false;
}
  
// Driver code
$n = 5;
isToOne($n)? print("Yes") : print("No");
  
// This code is contributed by princiraj1992
?>


输出:

Yes

上面的程序效率低下。这个想法是使用Collatz猜想。它指出如果n为正数,则在一定时间后它将以某种方式达到1。因此,通过使用这一事实,可以在O(1)中完成,即仅检查n是否为正整数。
请注意,对于负数,答案将是错误的。对于负数,上述操作将使数字保持负数,并且永远不会达到1。

C++

// C++ program to implement Collatz Conjecture
#include
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

 0)
        return true;
    return false;
}
  
// Driver code
$n = 5;
isToOne($n)? print("Yes") : print("No");
  
// This code is contributed by princiraj1992
?>

输出:

Yes

我们强烈建议将以下问题称为练习:

最大Collatz序列长度