Problem Statement

Write a program to print the sum of the first n prime numbers, where n is provided as input from the user.

Handling Input

x = int(input("Enter a positive integer: "))
while x <= 0:
    print("Invalid input!")
    x = int(input("Enter a positive integer: "))
n = x

Prime Numbers

for i in range(2, x):

Prime Numbers

for i in range(2, x):
    if x % i == 0:
        # i equally divides x

Prime Numbers

is_prime = True
for i in range(2, x):
    if x % i == 0:
        is_prime = False
# what if we get here?

Prime Numbers

is_prime = True
for i in range(2, x):
    if x % i == 0:
        is_prime = False
        <break
# what if we get here?

Prime Numbers

is_prime = True
for i in range(2, x):
    if x % i == 0:
        is_prime = False
# is_prime stores whether nx is prime or not

Full Program

x = int(input("Enter a positive integer: "))
while x <= 0:
    print("Invalid input!")
    x = int(input("Enter a positive integer: "))
n = x
count = 0 x = 2 total = 0 while count < n: is_prime = True for i in range(2, x): if x % i == 0: is_prime = False if is_prime: total = total + x count = count + 1 x = x + 1 print(f"The sum of the first {n} prime numbers is {total}")

Testing

  • Input Code
  • Outer While Loop
  • Inner For Loop


2 + 3 + 5 + 7 + 11 + 13 + 17 + 19 + 23 = 100