我试图编写一个遵循这一行的程序(示例其工作方式); 用户输入:
Give lower limit: 1
Give upper limit: 10
程序应从1-10开始打印:
1 is not a valid start number.
2 is a prime number.
3 is a prime number.
4 is not a prime number, because 2 * 2 = 4
5 is a prime number.
...
10 is not a prime number, because 2 * 5 = 10
检查给定范围后,应打印:
10 numbers was examined, 4 of which were prime numbers
The last found prime number is 7
我试图解决这个问题已经很长时间了,我太沮丧了,失去了一切。如果有人对此有解决方案,我很乐意看到它并进行分析,同时还要从中学习。
感谢,这将是巨大的帮助!
答案 0 :(得分:0)
lower = int(input("Give lower limit: ")) # Get lower bound, must be an int
upper = int(input("Give upper limit: ")) # Get upper bound, must be an int
print() # Print an empty line
primes = [] # An array to store the primes in
for i in range(lower, upper+1): # Go through the range
if i == 1:
print("1 is not a valid start number")
else:
primeFlag = True # Will only remain as true if the number is prime
for div in range(2, i): # Go from 2 to the current number
if i % div == 0:
primeFlag = False # If this happens, it isnt prime
if(primeFlag): # If it is a prime
primes.append(i) # Add to primes array
print(i," is a prime number")
else:
print(i," is not a valid prime")
print((upper-lower+1), " numbers were examined, ", len(primes), " were prime numbers")
print("The last found prime number is ", primes[-1:])
会产生:
Give lower limit: 1
Give upper limit: 10
1 is not a valid start number
2 is a prime number
3 is a prime number
4 is not a valid prime
5 is a prime number
6 is not a valid prime
7 is a prime number
8 is not a valid prime
9 is not a valid prime
10 is not a valid prime
10 numbers were examined, 4 were prime numbers
The last found prime number is [7]
我希望这会有所帮助,它可以使您几乎获得所需的输出,请花一些时间来理解和学习。
答案 1 :(得分:0)
我首先创建了一个范围为low and high
的列表。从那里使用1
消除了is not a valid start
,然后我创建了一个简单的检查表,运行i % n
,其中n
是范围2, i
中的值。现在,如果all(check)
表示所有结果均返回非零值,则该数字为质数。如果不是,我声明数字不是素数,如果enumerate, start = 2
0 item
中的check is
不是项目,
真will return
idx { {1}} 0`的值来解释为什么它不是素数。
and you can use the
of that