0
Sum of all prime numbers between 1 & 100
upto = int(input("Find sum of prime numbers upto : ")) sum = 0 for num in range(2, upto + 1): i = 2 for i in range(2, num): if (int(num % i) == 0): i = num break; if i is not num: sum += num print("\nSum of all prime numbers upto", upto, ":", sum) Can anyone please help me to check this program.when i run this program and enter 100 it's showing the result is 1058 But the sum of all prime numbers upto 100 must be 1060.
3 Réponses
+ 1
if 2 is not 2:
Evaluates to false so 2 is never added to sum. Just start sum with a value of 2 and it should work fine. You can also then start the outer loop at 3.
0
ran=int(input("Enter the range : "))
sum=0
for i in range(2,ran+1,1):
count=0
for j in range(2,i,1):
if i%j==0:
count+=1
else:
continue
if count==0:
sum+=i
else:
continue
print(sum)
0
def is_prime(number):
"""Check if a number is prime."""
if number < 2:
return False
for i in range(2, int(number**0.5) + 1):
if number % i == 0:
return False
return True
def sum_of_primes(start, end):
"""Calculate the sum of prime numbers in the given range."""
prime_sum = 0
for num in range(start, end + 1):
if is_prime(num):
prime_sum += num
return prime_sum
# Define the range
start_range = 1
end_range = 100
# Calculate and print the sum of prime numbers in the specified range
result = sum_of_primes(start_range, end_range)
print(f"The sum of prime numbers between {start_range} and {end_range} is: {result}")