I have the following issue where my code successfully generates the first 100 primes but doesn't work afterwards. I'm not really sure what the issue is.
a=0
def isprime(n):
prime=True
for i in range(2,int(n**0.5)+1):
if n%i==0:
prime=False
break
return prime
def irpb(x):
javab=True
for i in range(2,int(x**0.5)+1):
if x%i==0:
javab=False
break
return javab
for d in range(2,1*10**6):
if isprime(d):
#print("D is ",d)
a+=d
if irpb(a):
if a<1*10**6:
print(a)
print("------Finish------")
Thank you for your help.
There is a logical error. You want to print the sum of all the primes from 1 to N. Fine. For sure if "N" is 10^6 the sum of all the primes from 1 to N is higher than 10^6. So your last condition:
if a<1*10**6:
print(a)
when you put a range that is:
for d in range(2,1*10**6):
will never be true.
Here a solution:
a=0
N=10^6
def isprime(n):
prime=True
for i in range(2,int(n**0.5)+1):
if n%i==0:
prime=False
break
return prime
for d in range(2,N):
if isprime(d):
print("D is ",d)
a+=d
if(N<=10^6)
print(a)
Output:
37550402023
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.