[英]How do I find all primes in a user-defined range?
I want to get a script to: a) check if a number within the user defined range is prime or not b) print the result of a check c) print amount of numbers checked and how many of these numbers were primes d) print the last prime number我想要一个脚本来:a)检查用户定义范围内的数字是否为素数 b)打印检查结果 c)打印检查的数字数量以及这些数字中有多少是素数 d)打印最后一个素数
Here is what I have so far:这是我到目前为止所拥有的:
lower = int(input("Lower boundry: "))
upper = int(input("Upper boundry: "))
for n in range(lower, upper + 1):
if (n <= 1):
print(n, "error")
elif (n > 1):
for x in range(2, n):
if ((n % x) == 0):
print(n, "not prime, because", x, "*", int(n/x),"=", n)
break
else:
print(n, "prime")
last = [n]
print("Checked", n, "numbers, of which","XXX","were prime.")
print("Last prime number found was", *last)
Question:问题:
The tool im using gives me an error.我使用的工具给了我一个错误。 Lets say, I check the numbers 1-10.
可以说,我检查数字 1-10。 On 1 I get a notification that 1 is not prime (as intended, as n <= 1).
在 1 上,我收到 1 不是素数的通知(如预期的那样,如 n <= 1)。 Number 2 is a prime and the programme notifies me of this.
数字 2 是一个素数,程序会通知我这一点。 However, on 3 i get an error - "incorrect output: your program printed "prime3", but should have printed "prime.". I don't get it. Is it the white space python seems to like so much? Or did I fail with else if use?
但是,在 3 上,我收到一个错误 - “不正确的 output:您的程序打印了“prime3”,但应该打印了“prime”。我不明白。是空格 python 似乎很喜欢吗?还是如果使用,我会失败吗?
For checking the number of primes within the specified range - am I supposed to use a list to store the values generated in the for loop?为了检查指定范围内的素数数量 - 我应该使用列表来存储 for 循环中生成的值吗? The material will cover lists during later sessions, so I am guessing I am meant to use some other method.
该材料将在以后的会议中涵盖列表,所以我猜我打算使用其他方法。 But lets say I want to use the list.
但是可以说我想使用列表。 Is it something like:
是不是像:
list=[] for y in [1,10]: for z in [0,1,2,3]: x=y+z list.append(x)
and the use len(list) where the XXX placeholder is ATM?以及 XXX 占位符是 ATM 的使用 len(list)?
Edit: Got the c) and d) to work - used list as a storage for values.编辑:让 c) 和 d) 工作 - 使用列表作为值的存储。 Printed last value in the list for d) and used the length of the list for c).
为 d) 打印列表中的最后一个值,并为 c) 使用列表的长度。 Fixed the indentation issue pointed out to me in the comments below.
修复了以下评论中向我指出的缩进问题。 Still cannot get the code to run properly.
仍然无法让代码正常运行。 In I in put 1 and 10 as bounds, the programme identifies 1 as not prime, 2 as prime and then gives error.
在 I 中,将 1 和 10 作为界限,程序将 1 识别为非质数,将 2 识别为质数,然后给出错误。 Error text is: "Incorrect output: your program printed "prime3", but should have printed "prime." " Not really sure what is up with that.
错误文本是:“不正确的 output:您的程序打印了“prime3”,但应该打印了“prime”。“不太确定这是怎么回事。
Fist of all: Please pose your question in the title.首先:请在标题中提出您的问题。 For Example: "How do I find all primes in a user-defined range?"
例如:“如何找到用户定义范围内的所有素数?”
To find out whether or not a number is prime you can divide it by all primes smaller than the number, since all non-primes can be divided by primes.要确定一个数字是否为素数,您可以将其除以所有小于该数字的素数,因为所有非素数都可以除以素数。 This is significantly faster than checking all numbers
这比检查所有数字要快得多
I would first define a function to generate the next prime.我将首先定义一个 function 来生成下一个素数。 For this I take the last prime number and then continue to add 2 to it until we find the next prime:
为此,我取最后一个素数,然后继续向其添加 2,直到找到下一个素数:
def dividable_by_any_in_list(x, list):
for n in list:
if x%n == 0:
return True
return False
def next_prime(known_primes):
"""
Takes a list of known primes and returns the next prime.
"""
current = known_primes[-1]+2
while True:
if dividable_by_any_in_list(current, known_primes):
current += 2
else:
return current
I tested that with this main function:我用这个主要的 function 进行了测试:
def main():
# Not what you want to copy-paste
known_primes = [2,3,5,7,11,13,17,19]
next = next_prime(known_primes)
print(next)
if __name__ == '__main__':
main()
and it returned 23, which is correct.它返回 23,这是正确的。
Now we can write a function to find all primes below an upper boundary:现在我们可以编写一个 function 来查找上边界以下的所有素数:
def find_primes_below(known_primes, max):
last = known_primes[-1]
while last <= max:
last = next_prime(known_primes)
known_primes.append(last)
return known_primes[:-1]
Using this we can write a function that takes the return value of this function and cuts out all primes below the lower bound:使用它,我们可以编写一个 function ,它获取此 function 的返回值并删除下限以下的所有素数:
def find_primes_in_range(known_primes, min, max):
all_primes = find_primes_below(known_primes, max)
l = 0
while all_primes[l] < min:
l+=1
u = len(all_primes)-1
while all_primes[u] > max:
u -= 1
return all_primes[l:u]
Now we can define the main function:现在我们可以定义主function:
def main():
known_primes = [2,3,5,7,11,13,17,19]
lower = int(input("Lower boundry: "))
upper = int(input("Upper boundry: "))
primes = find_primes_in_range(known_primes, lower, upper)
print("Found Primes:")
print(primes)
print(f"Checked {upper-lower} numbers, of which {len(primes)} were prime.")
print("Last prime number found was", primes[-1])
if __name__ == '__main__':
main()
How about this.这个怎么样。
# define a flag variable
lower = int(input("Lower boundry: "))
upper = int(input("Upper boundry: "))
prime_list=[]
for num in range(lower,upper+1):
flag = False
# prime numbers are greater than 1
if num > 1:
# check for factors
for i in range(2, num):
if (num % i) == 0:
# if factor is found, set flag to True
flag = True
# break out of loop
break
# check if flag is True
if flag:
flag=False
else:
prime_list.append(num)
print("Checked:",len(list(range(lower,upper+1))),"numbers where",len(prime_list),"were prime.")
print("Last prime number checked: ",prime_list[-1])
print("All prime numbers are: ",','.join(str(n) for n in prime_list))
Output Output
Lower boundry: 1
Upper boundry: 30
Checked: 30 numbers where 11 were prime.
Last prime number checked: 29
All prime numbers are: 1,2,3,5,7,11,13,17,19,23,29
The indentation of your else
clause is wrong.你的
else
子句的缩进是错误的。 It should belong to the for
loop.它应该属于
for
循环。 This means it will be executed when the loop is not terminated by the break
statement.这意味着它将在循环未被
break
语句终止时执行。
I can't answer your question about the error message, because I don't know the test tool in question.我无法回答您关于错误消息的问题,因为我不知道有问题的测试工具。
To keep track of the number of primes found, you can use a simple integer variable: Initialize it as zero and increment it by 1 whenever a prime is found.要跟踪找到的素数数量,您可以使用简单的 integer 变量:将其初始化为零并在找到素数时将其增加 1。
lower = int(input("Lower boundry: "))
upper = int(input("Upper boundry: "))
n_primes = 0
for n in range(lower, upper + 1):
if (n <= 1):
print(n, "error")
else:
for x in range(2, n):
if ((n % x) == 0):
print(n, "not prime, because", x, "*", int(n/x),"=", n)
break
else:
print(n, "prime")
n_primes += 1
last = n
print("Checked", upper - lower + 1, "numbers, of which", n_primes, "were prime.")
print("Last prime number found was", last)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.