I am currently solving a mathematical problem in which I need to count the number of reduced proper fractions with both numerator and denominator more more than 1000000 (10^6).
I have code that works fine for small numbers; the example given (value=8) gives the correct (given) answer 21.
But this code seems to be very slow for big numbers for reasons I don't know. I read a whole bunch of similar questions on SO, but couldn't find anything that was useful. I had a closer look at this and this, but that didn't really help me out. My code works with acceptable speed for values until 1000, then it gets super-super-slow.
import math
def is_prime(n):
if n == 2:
return True
if n % 2 == 0 or n <= 1:
return False
sqr = int(math.sqrt(n)) + 1
for divisor in range(3, sqr, 2):
if n % divisor == 0:
return False
return True
def get_divisors(n):
liste = [1]
if n % 2 == 0:
liste.append(2)
for divisor in range(3, n+1):
if n % divisor == 0:
liste.append(divisor)
return liste
def intersect(a, b):
return list(set(a) & set(b))
until = 1000
primes = list()
for i in range(int(until)):
if i != 1 and i != 0:
if is_prime(i):
primes.append(i)
pos = 0
for i in range(1, until+1):
if i%50 == 0:
print(i)
if is_prime(i):
pos += (i-1)
else:
di = get_divisors(i)
di.remove(1)
for j in range(1, i):
dj = get_divisors(j)
if intersect(di, dj)==[]:
pos+=1
print(pos)
I want to know which parts of my program are reducing the speed and how to fix these issues.