显示所有奇数而不是质数
Showing all odd numbers instead of prime numbers
def prime_num_gen():
try:
r = int(input('Type in the number till which you want to generate your prime numbers : '))
if r <= 2:
print('There is no prime number smaller than 2, 2 is the smallest prime number')
#A list to store primes
#Storing 2 already, because I need a number to start with
prime_num = [2]
#Counter
#Counter will be divided and if it's a prime; will append it
x = 3
#Starting with 3 cus 2 is already considered
#Having a jump of 2, cus no even num is prime, so considering only odd nums
while x <= r:
for num in range(3,x,2):
if num % x == 0:
x += 2
break
else:
prime_num.append(x)
x += 2
print(prime_num)
except:
print('Please only give input as a number!\nTry again')
出于某种原因,此代码将所有奇数都包含为素数。我是编码方面的新手,即使这看起来是一个非常明显的错误,也请告诉我。
任何帮助将不胜感激!!
您的代码中有一个小错误。而不是条件
if num % x == 0:
你应该做
if x % num == 0:
由于 num 总是小于或等于 x,所以它对 x 的模数总是再次给出数字。
这里是一个略有不同的实现,可以在不同的范围内更快。 基本算法很简单。
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i == 0:
return False
return True
for i in range (1,100):
if isprime(i) == True:
print(i)
找到所有小于 N 的素数需要 O(N log (log N)) 时间。
def prime_num_gen():
try:
r = int(input('Type in the number till which you want to generate your prime numbers : '))
if r <= 2:
print('There is no prime number smaller than 2, 2 is the smallest prime number')
#A list to store primes
#Storing 2 already, because I need a number to start with
prime_num = [2]
#Counter
#Counter will be divided and if it's a prime; will append it
x = 3
#Starting with 3 cus 2 is already considered
#Having a jump of 2, cus no even num is prime, so considering only odd nums
while x <= r:
for num in range(3,x,2):
if num % x == 0:
x += 2
break
else:
prime_num.append(x)
x += 2
print(prime_num)
except:
print('Please only give input as a number!\nTry again')
出于某种原因,此代码将所有奇数都包含为素数。我是编码方面的新手,即使这看起来是一个非常明显的错误,也请告诉我。
任何帮助将不胜感激!!
您的代码中有一个小错误。而不是条件
if num % x == 0:
你应该做
if x % num == 0:
由于 num 总是小于或等于 x,所以它对 x 的模数总是再次给出数字。
这里是一个略有不同的实现,可以在不同的范围内更快。 基本算法很简单。
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i == 0:
return False
return True
for i in range (1,100):
if isprime(i) == True:
print(i)
找到所有小于 N 的素数需要 O(N log (log N)) 时间。