[英]find prime numbers in python
我需要編寫一個代碼來找到一系列數字中的所有質數,然后按順序列出它們,說明哪些是質數,哪些不是,如果它們不是質數,則顯示它們可以被哪些數字整除。 它應該看起來像這樣:
>>> Prime(1,10)
1 is not a prime number
2 is a prime number
3 is a prime number
4 is divisible by 2
5 is a prime number
6 is divisible by 2, 3
7 is a prime number
8 is divisible by 2, 4
9 is divisible by 3
到目前為止,我有這個只會識別哪些數字是素數並將它們打印在列表中。 我不知道如何計算非質數並打印它可以被哪些數字整除。 我也知道 1 是質數。
def primeNum(num1, num2):
for num in range(num1,num2):
prime = True
for i in range(2,num):
if (num%i==0):
prime = False
if prime:
print (num,'is a prime number')
使用篩子可以達到目的:
例:
from __future__ import print_function
def primes():
"""Prime Number Generator
Generator an infinite sequence of primes
http://stackoverflow.com/questions/567222/simple-prime-generator-in-python
"""
# Maps composites to primes witnessing their compositeness.
# This is memory efficient, as the sieve is not "run forward"
# indefinitely, but only as long as required by the current
# number being tested.
#
D = {}
# The running integer that's checked for primeness
q = 2
while True:
if q not in D:
# q is a new prime.
# Yield it and mark its first multiple that isn't
# already marked in previous iterations
#
yield q
D[q * q] = [q]
else:
# q is composite. D[q] is the list of primes that
# divide it. Since we've reached q, we no longer
# need it in the map, but we'll mark the next
# multiples of its witnesses to prepare for larger
# numbers
#
for p in D[q]:
D.setdefault(p + q, []).append(p)
del D[q]
q += 1
def factors(n):
yield 1
i = 2
limit = n**0.5
while i <= limit:
if n % i == 0:
yield i
n = n / i
limit = n**0.5
else:
i += 1
if n > 1:
yield n
def primerange(start, stop):
pg = primes()
p = next(pg)
for i in xrange(start, stop):
while p < i:
p = next(pg)
if p == i:
print("{0} is prime".format(i))
else:
print("{0} is not prime and has factors: {1}".format(i, ", ".join(map(str, set(factors(i))))))
輸出:
>>> primerange(1, 10)
1 is not prime and has factors: 1
2 is prime
3 is prime
4 is not prime and has factors: 1, 2
5 is prime
6 is not prime and has factors: 1, 2, 3
7 is prime
8 is not prime and has factors: 1, 2
9 is not prime and has factors: 1, 3
您可以將每個數字的除數存儲在列表中,然后使用", ".join(yourList)
打印
即:
def primeNum(num1, num2):
for num in range(num1,num2):
divisors = []
for i in range(2,num):
if (num%i == 0):
divisors.append(str(i))
if divisors:
print ('%d is divisible by ' %num + ', '.join(divisors))
else:
print ('%d is a prime number' %num)
編輯:愚蠢的語法錯誤
只需在將prime設置為false的位置添加打印和中斷即可。
一個更優雅的解決方案是制作一個單獨的函數isPrime或在內部for循環中使用break和else。 兩種方式都將使質數不必要。
您只能一一除以它本身,因此至少是該定義,它是質數。
> # Check a number whether prime or not
a = int(input("Please your number (>1): "))
y = 2
import math
b = math.floor(math.sqrt(a)) + 1
x = True
while x:
if a == 2:
print(f'{a} is prime')
x = False
else:
x = True
if a %y == 0:
print(f' {a} is not prime')
x = False
else:
y = y + 1
if y >= b:
print(f'{a} is prime')
x = False
else:
x = True
這是輸出的簡單程序
def isPrime(lower,upper):
for num in range(lower,upper+1):
if num > 1:
for i in range(2,num):
if (num % 1) == 0:
break
else:
print(num," is a prime number")
def isDivisible(lower,upper):
for num in range(lower,upper+1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
print(num," is divisible by ", i)
else:
pass
else:
pass
Lower = int(input("Enter your Lower limit"))
Upper = int(input("Enter Your Upper Limit"))
isPrime(Lower,Upper)
isDivisible(Lower,Upper)
**This is the output to code:**
2 is a prime number
4 is divisible by 2
6 is divisible by 2
6 is divisible by 3
8 is divisible by 2
8 is divisible by 4
9 is divisible by 3
10 is divisible by 2
10 is divisible by 5
這段代碼從用戶那里接收一個數字並判斷它是否是質數。 我可以說它是最快的,因為在數學中,要找出一個數字是否是素數,只需檢查該數字的平方根就足夠了。
import math
prime = int(input("Enter your number: "))
count = 0
sqr = int(math.sqrt(prime))
for i in range(2, sqr+1):
if prime % i == 0:
print("your number is not prime")
count += 1
break
if count == 0:
print("your number is prime")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.