I'm having trouble with the computation time. Does anyone have any ideas for faster code?
#prints a list of tuples containing the solutions to x^2+y^2=p where p is a prime less than a million
i=10^6
primeswithsolutions=[]
for x in range(i):
for y in range(i):
w=(x^2)+(y^2)
if is_prime(w)==True and w<i:
solution=(x,y,w)
primeswithsolutions.append(solution)
print primeswithsolutions
Thank you for any help you can provide.
Answered: Realized it was just the range that was messed up.
Thank you!
#prints a list of tuples containing the solutions to x^2+y^2=p where p is a prime less than a million
i=10^3
primeswithsolutions=[(1, 1, 2)]
for x in range(i):
if is_even(x)==True:
for y in range(x,i):
if is_odd(y)==True:
w=(x^2)+(y^2)
if is_prime(w)==True and w<(i^2):
solution=(x,y,w)
primeswithsolutions.append(solution)
print primeswithsolutions
y in range(i)
, you can have the statementy in range(x, i)
. You could also do some divisibility tests; only execute the code if $\gcd(x, y) = 1$, otherwise their sum of squares will be divisible by that $\gcd$. (Note: I have no idea if divisibility tests are any quicker than the tests you're running in the loop; it might not save time, but it probably would). – pjs36 Apr 11 '15 at 01:09