给定数字N,任务是使用Wilson Primality Test检查它是否为质数。如果数字是素数,则打印“ 1”,否则打印“ 0”。
威尔逊定理指出,当且仅当自然数p> 1为素数
(p - 1) ! ≡ -1 mod p
OR (p - 1) ! ≡ (p-1) mod p
例子:
Input: p = 5
Output: Yes
(p - 1)! = 24
24 % 5 = 4
Input: p = 7
Output: Yes
(p-1)! = 6! = 720
720 % 7 = 6
以下是Wilson Primality Test的实施
C++
// C++ implementation to check if a number is
// prime or not using Wilson Primality Test
#include
using namespace std;
// Function to calculate the factorial
long fact(const int& p)
{
if (p <= 1)
return 1;
return p * fact(p - 1);
}
// Function to check if the
// number is prime or not
bool isPrime(const int& p)
{
if (p == 4)
return false;
return bool(fact(p >> 1) % p);
}
// Driver code
int main()
{
cout << isPrime(127);
return 0;
}
Java
// Java implementation to check if a number is
// prime or not using Wilson Primality Test
public class Main
{
// Function to calculate the factorial
public static long fact(int p)
{
if (p <= 1)
return 1;
return p * fact(p - 1);
}
// Function to check if the
// number is prime or not
public static long isPrime(int p)
{
if (p == 4)
return 0;
return (fact(p >> 1) % p);
}
public static void main(String[] args) {
if(isPrime(127) == 0)
{
System.out.println(0);
}
else{
System.out.println(1);
}
}
}
// This code is contributed by divyesh072019
Python3
# Python3 implementation to check if a number is
# prime or not using Wilson Primality Test
# Function to calculate the factorial
def fact(p):
if (p <= 1):
return 1
return p * fact(p - 1)
# Function to check if the
# number is prime or not
def isPrime(p):
if (p == 4):
return 0
return (fact(p >> 1) % p)
# Driver code
if (isPrime(127) == 0):
print(0)
else:
print(1)
# This code is contributed by rag2127
C#
// C# implementation to check if a number is
// prime or not using Wilson Primality Test
using System;
class GFG {
// Function to calculate the factorial
static long fact(int p)
{
if (p <= 1)
return 1;
return p * fact(p - 1);
}
// Function to check if the
// number is prime or not
static long isPrime(int p)
{
if (p == 4)
return 0;
return (fact(p >> 1) % p);
}
static void Main() {
if(isPrime(127) == 0)
{
Console.WriteLine(0);
}
else{
Console.WriteLine(1);
}
}
}
// This code is contributed by divyeshrabadiya07
Javascript
输出:
1
它是如何工作的?
- 我们可以快速检查p = 2或p = 3的结果。
- 对于p> 3:如果p是合成的,则其正除数在整数1,2,3,4,…,p-1之间,并且很显然gcd((p-1)!, p)> 1 ,所以我们不能拥有(p-1)! = -1(mod p)。
- 现在让我们看一下当p为质数时,它究竟是-1。如果p是质数,则[1,p-1]中的所有数字都相对于p质数。并且对于范围[2,p-2]中的每个数字x,必须存在一个对y,使得(x * y)%p = 1。
[1 * 2 * 3 * ... (p-1)]%p
= [1 * 1 * 1 ... (p-1)] // Group all x and y in [2..p-2]
// such that (x*y)%p = 1
= (p-1)