如何在Python中求出一定范围内的素数之和?

cuxqih21  于 2022-12-24  发布在  Python
关注(0)|答案(3)|浏览(208)

我对Python和一般编程都是新手,所以如果有人能给初学者给予非常友好的帮助,我会很有帮助的,我正试图得到质数的和,比如说50。
我使用了下面的代码,但它增加了额外的2对我的总和。例如,质数的总和高达50应该是326,但我得到328作为我的输出

upto = int(input("Find sum of prime numbers upto : "))

sum = 0

for num in range(2, upto + 1):

    
    for i in range(2, num):
        if (int(num % i) == 0):
            break;

    #If the number is prime then add it.
    else:
        sum += num

print("\nSum of all prime numbers upto", upto, ":", sum)
disbfnqx

disbfnqx1#

您的代码工作正常良好,"* 1到50之间的质数之和 "的答案是328而不是326,如果您对此仍有疑问,可以使用下面的代码检查您的结果:
说明:
给定一个范围[l, r] *,任务是求出该范围内所有质数的和。

# from math lib import sqrt method
from math import sqrt

# Function to compute the prime number
def checkPrime(numberToCheck) :

    if numberToCheck == 1 :
        return False

    for i in range(2, int(sqrt(numberToCheck)) + 1) :

        if numberToCheck % i == 0 :
            return False

    return True

# Function to iterate the loop
# from l to r. If the current
# number is prime, sum the value
def primeSum(l, r) :

    sum = 0

    for i in range(r, (l - 1), -1) :

        # Check for prime
        isPrime = checkPrime(i)
        
        if (isPrime) :

            # Sum the prime number
            sum += i

    return sum



# Driver code   
if __name__ == "__main__" :

    l, r = 1, 50

    # Call the function with l and r
    print(primeSum(l, r))

我在上面的代码中设置了你的范围,只需复制并粘贴代码到你的编辑器中并运行代码,你就会看到结果。

djmepvbi

djmepvbi2#

有两个部分需要处理。一个是检查数字是否为质数。第二个是迭代数字的范围。请参考下面的代码,

from math import sqrt

sum = 0
#some explanation here we are iterating from 50 all the way to 1. So you can indicate your range here. -1 is the step value which tells the difference between each iteration.
for i in range(50, 0, -1):

    # Check whether it is a prime number here
    bPrime = True  #initialize a boolean here to be indicated by the loop below
    for a in range(2, int(sqrt(i)) + 1):
        if i % a == 0:
            bPrime = False    #definitely not a prime,break the loop and set boolean to false
            break
        bPrime = True         #not ==0 so it is a prime, set boolean to true
        
    if (bPrime) :
        # Add up if it is a prime number
        sum += i
        
#view the results 
print(sum)

你应该能拿到328

oxosxuxt

oxosxuxt3#

您好Sumit首先欢迎Stackoverflow:)
现在根据你的问题,50以内的质数之和只有328,而不是326。
但是如果你想要前50个质数的总和,那么你可以在你的代码中做一些小的改变,如下所示,这将给予你326****[这是奇质数的总和,直到范围50]

upto = int(input("Find sum of prime numbers upto : "))

sum = 0

for num in range(3, upto+1):

    
    for i in range(2, num):
        if (int(num % i) == 0):
            break;

    #If the number is prime then add it.
    else:
        sum += num

print("\nSum of all prime numbers upto", upto, ":", sum)

相关问题