Use the function to realize the sum of all prime numbers between (50~100)

The following is the code implementation of Python:

def is_prime(num):
    if num < 2:
        return False
    for i in range(2, int(num ** 0.5) + 1):
        if num % i == 0:
            return False
    return True

def sum_primes(start, end):
    primes_sum = 0
    for num in range(start, end+1):
        if is_prime(num):
            primes_sum += num
    return primes_sum

# 测试
start, end = 50, 100
primes_sum = sum_primes(start, end)
print(f"{start}~{end}之间所有素数的和为:", primes_sum)

To explain the code:

  • Lines 2-8 define a is_primefunction called , which is used to determine whether an integer is prime. According to the definition of prime number, all numbers less than 2 are not prime numbers. For a number greater than or equal to 2, if there is no other integer in the range of (2, root sign n] that can divide it, then it is a prime number.
  • Lines 10 and 15 define a function called `sum_primes` that takes the starting and ending numbers as input parameters. The title requires calculating the sum of prime numbers between 50 and 100, so the default input start and end numbers here are 50 and 100 respectively.
  • Line 12 creates a variable primes_suminitialized to 0 to store the sum of all prime numbers.
  • Lines 13-15 judge whether the current number is a prime number during the loop process, and if so, add it to primes_sum.
  • Line 16 uses returnthe statement to return the sum of all prime numbers computed as the result.
  • Lines 19-21 call sum_primesthe function and store the returned result in a variable primes_sum.
  • Finally output relevant information.

Note: When judging whether an integer is a prime number, you only need to check the numbers from 2 to the root sign n. This is because if n is divisible by m, then m must have a corresponding factor k, and k is also divisible by n/m. At least one of these factors is less than or equal to root n and another factor is greater than or equal to root n. Therefore, if we have traversed to the root sign n and have not found a factor that can divide n evenly, then n must be a prime number.

Guess you like

Origin blog.csdn.net/qq_51447496/article/details/130733984
Recommended