Instead of the sum of prime numbers the output is the sum of all the numbers between the interval Here is my code:
x=int(input("lower limit"))
y=int(input("upper limit"))
s=0
for i in range(x, y 1):
for j in range(2,int(i ** (0.5)) 1):
if i % j == 0:
break
s = i
print(s)
CodePudding user response:
You were adding i
on every loop iteration(whether there are any factors other than 1 and itself). Instead, add i
only when the factor is 1 and i
:
x=int(input("lower limit"))
y=int(input("upper limit"))
s=0
for i in range(x, y 1):
for j in range(2,int(i ** (0.5)) 1):
if i % j == 0:
break
else:
s = i
print(s)
Output:
lower limit2
upper limit10
17
CodePudding user response:
We can use a variable found
which we reset to 0 before each number tested.
x=int(input("lower limit"))
y=int(input("upper limit"))
s=0
for i in range(x, y 1):
found=0
for j in range(2,int(i ** (0.5)) 1):
if i % j == 0:
found=1
if found==0:
print("adding",i)
s = i
print(s)
Example run
lower limit2
upper limit7
adding 2
adding 3
adding 5
adding 7
17
CodePudding user response:
A possible problem with your code, making it harder to debug, is that it is not divided into functions.
Your basic operation is checking if a number is prime, so you should define a function is_prime
checking if an integer is prime.
def is_prime(n):
for j in range(2,int(i ** (0.5)) 1):
if i % j == 0:
return False
return True
Once you have a function, you can test it and check if it works.
After that, you can use your building block and create a more readable and debuggable code:
x=int(input("lower limit"))
y=int(input("upper limit"))
s=0
for i in range(x, y 1):
if is_prime(i):
s = i
print(s)
If can use external packages, there's an implementation for is_prime
in the packages sympy
and primePy
- comparing your results to these implementations is also a good way to test your code.