这种方法基于威尔逊定理,并且利用DP可以轻松完成阶乘计算这一事实。
威尔逊定理说,如果数k为质数,则((k-1)!+ 1)%k必须为0。
以下是该方法的Python实现。请注意,该解决方案在Python有效,因为默认情况下Python支持大整数,因此可以计算大数阶乘。
C++
// C++ program to Prints prime numbers smaller than n
#include
using namespace std;
void primesInRange(int n)
{
// Compute factorials and apply Wilson's
// theorem.
int fact = 1;
for(int k=2;k
Java
// Java program prints prime numbers smaller than n
class GFG{
static void primesInRange(int n)
{
// Compute factorials and apply Wilson's
// theorem.
int fact = 1;
for(int k=2;k
Python3
# Python3 program to prints prime numbers smaller than n
def primesInRange(n) :
# Compute factorials and apply Wilson's
# theorem.
fact = 1
for k in range(2, n):
fact = fact * (k - 1)
if ((fact + 1) % k == 0):
print k
# Driver code
n = 15
primesInRange(n)
C#
// C# program prints prime numbers smaller than n
class GFG{
static void primesInRange(int n)
{
// Compute factorials and apply Wilson's
// theorem.
int fact = 1;
for(int k=2;k
PHP
Javascript
输出 :
2
3
5
7
11
13