简体   繁体   English

在 Python 中使用递归的素数总和

[英]Sum of Prime using Recursion in Python

The problem given is to determine whether two numbers m and n are prime or not, and if they are, give the sum of all prime numbers from m to n.给出的问题是确定两个数 m 和 n 是否为素数,如果是,则给出从 m 到 n 的所有素数之和。 I have already made a code for the first part:我已经为第一部分制作了代码:

def isPrime(n, i):
    if n <= i:
        return True if (n == 2) else False
    if n % i == 0:
        return False
    if i * i > n:
        return True
    return isPrime(n, i + 1)

However, I don't know how to do the second part of the code.但是,我不知道如何执行代码的第二部分。 A clue that our professor gave to us was to call the first function in the second part of the code, like this:我们教授给我们的一个线索是在代码的第二部分调用第一个function,如下所示:

def sumOfPrime(m, n):
    **enter code here**
        isPrime(m, 2)
        isPrime(n, 2)

I've no idea how to know all the prime numbers from m to n.我不知道如何知道从 m 到 n 的所有素数。 Also, we are only allowed to use recursion for this problem.此外,我们只允许对这个问题使用递归。

I assume your professor wants you to just test all numbers between m and n for primality, then add those that pass together.我假设您的教授希望您仅测试mn之间的所有数字的素数,然后将通过的数字相加。

def sumOfPrime(m, n):
    if isPrime(m, 2) and isPrime(n, 2):
        return sum(i for i in range(m, n + 1) if isPrime(i, 2))

Here is a fully recursive version:这是一个完全递归的版本:

def sumOfPrime(m,n):
    if isPrime(n,2) and isPrime(m,2):
        return sumOfPrimes(m,n)

def sumOfPrimes(m, n):
    if m > n:
        return 0
    return (m if isPrime(m,2) else 0) + sumOfPrimes(m+1,n)

If only one function, maybe better with a nestet function:如果只有一个 function,最好用一个嵌套 function:

def sumOfPrime(m,n):
    def helper(m,n):
        if m > n:
            return 0
        return (m if isPrime(m,2) else 0) + sumOfPrimes(m+1,n)

    if isPrime(n,2) and isPrime(m,2):
        return helper(m,n)


assert sumOfPrime(2,5) == 2 +3 + 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM