写一个Python程序来打印一个区间内的所有质数?

k7fdbhmy  于 2022-12-28  发布在  Python
关注(0)|答案(4)|浏览(252)

定义一个函数,它接受两个整数(开始,结束),并将范围内的数字分类为质数和非质数,并打印质数

def is_prime(n):
    if n < 1: 
        return False 
    for i in range(2, n+1): 
        if n % i == 0: 
            return False 
    return True 
 
def print_primes(start, end): 
    for i in range(start, end): 
        if is_prime(i): 
            print(i) 
 
a=int(input("Start value: ")
b=int(input("End value: ")
print_primes(a,b)
iezvtpos

iezvtpos1#

def is_prime(n): 
    if n < 2: 
        return False 
    for i in range(2, n): 
        if n % i == 0: 
            return False 
    return True 
 
def print_primes(start, end): 
    for i in range(start, end+1): 
        if is_prime(i): 
            print(i) 
 
a=int(input("Start value:")
b=int(input("End value:")
print_primes(a,b)
q5iwbnjs

q5iwbnjs2#

    • 一些已修复的错误。**

(1)从用户ab获取输入时,您尚未关闭round参数
(2)is_prime(). for循环运行到n-1,而不是运行到n
(3)将答案存储在res中,以提高可读性。

    • 代码:-**
def is_prime(n):
    if n < 1: 
        return False 
    for i in range(2, n): 
        if n % i == 0: 
            return False 
    return True 
 
def print_primes(start, end):
    res=[]
    for i in range(start, end): 
        if is_prime(i): 
            res.append(i)
    return res
 
a=int(input("Start value: "))
b=int(input("End value: "))
print(print_primes(a,b))
    • 输出:**
Start value: 3
End value: 13
[3, 5, 7, 11]

正如您所看到的,起始值是包含的,而结束值是排除的,以使两个包含的值都在print_primes函数中迭代到end+1

vs3odd8k

vs3odd8k3#

def is_prime(n):
    if n < 1: 
        return False 
    for i in range(2, n+1):

它应该是:

def is_prime(n):
    if n < 1: 
        return False 
    for i in range(2, n):

它应该一直运行到小于n,否则n将始终被i整除,并返回False

a=int(input("Start value:"))  # make sure to close the parenthesis
b=int(input("End value:"))    # make sure to close the parenthesis
vs3odd8k

vs3odd8k4#

这考虑到了范围内的浮点数问题。试试吧。:)

def is_prime(n):    
    if not n < 1:      
        for i in range(2, n): 
            if not n % i == 0:
                return True
            else:
                return False

    
def print_primes(start, end):
    res=[]
    start=int(start)
    end=int(end)
    for i in range(start, end+1):
        if is_prime(i): 
            res.append(i)
    return res
    
#a=int(input("Start value: "))
#b=int(input("End value: "))
a=0.3
b=41
print_primes(a,b) 
#[3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41]

相关问题