To find the sum of the first 50 prime numbers, I need to first generate the first 50 prime numbers and then sum them. I'll use a function to efficiently generate prime numbers and then sum the results.
Code:
def is_prime(n):
"""Checks if a number is prime."""
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def generate_primes(n):
"""Generates the first n prime numbers."""
primes = []
num = 2
while len(primes) < n:
if is_prime(num):
primes.append(num)
num += 1
return primes
first_50_primes = generate_primes(50)
sum_of_primes = sum(first_50_primes)
print(f"The first 50 prime numbers are: {first_50_primes}")
print(f"The sum of the first 50 prime numbers is: {sum_of_primes}")
Execution Result:
The first 50 prime numbers are: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229]
The sum of the first 50 prime numbers is: 5117
The code generates the first 50 prime numbers and then calculates their sum. The `is_prime` function efficiently checks for primality, and the `generate_primes` function iteratively adds primes to a list until 50 are found. The final sum is then computed. The output shows both the list of primes and their sum, confirming the calculation.