Answer to Question #179151 in Python for phani

Question #179151
Sum of Prime Numbers from M to N
Given two integers M and N, write a program to print the sum of prime numbers from M to N.
Input

The first line of input will contain a positive integer (M).
The second line of input will contain a positive integer (N).
Output

The output should be a single line containing the sum of prime numbers from M to N.
Explanation

For example, if the given M and N are 5 and 11, as all the prime numbers from 5 to 11 are 5, 7, and 11. So the output should be sum of these primes (5+7+11), which is 23.

Similarly, if the given numbers are M is 18 and N is 40, as all the prime numbers from 18 to 40 are 19, 23, 29, 31,and 37. So the output should be sum of these primes (19+23+29+31+37), which is 139.

Sample Input 1
5
11
Sample Output 1
23

Sample Input 2
18
40
Sample Output 2
139


1
Expert's answer
2021-04-07T12:08:15-0400
def isPrime(n):
    if n % 2 == 0:
        return n == 2
    d = 3
    while d * d <= n and n % d != 0:
        d += 2
    return d * d > n


a, b, s = int(input()), int(input()), 0
for i in range(a, b + 1):
    if isPrime(i):
        s += i
print(s)

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS