List element removal occurring anyway after unsuccessful check in Python 2.7 -
i'm trying system of linear congruences solver moduli not coprime, requires me break each modulus down prime factorizations , compare them against each other create new system solvable. need break number down prime powers (ie 36 becomes 4*9 opposed 2*2*3*3) , compare against other modulus , remove overlapping prime powers (ie if 1 number has factor of 4 , other has factor of 2, remove factor of 2).
for reason, when run code, many factors getting removed regardless of whether smaller powers of prime power in other modulus. example (i've included below), when take moduli pair 1000142 , 1002045, number 1002045, has factorization of 3 * 5 * 11 * 6073 returns [6073] after checks run against it, though 2 moduli have no prime powers in common.
does know why might happening? i'm pretty sure is_prime , factorize methods correct - i've tested them extensively on ranges of numbers without issue. why items getting removed list when condition check fails?
please ignore totient , crt stuff - it's not important.
any advice appreciated!
import time itertools import combinations fractions import gcd def is_power(a, b): if > b: a, b = b, while != b: if b % != 0: return false b /= return true def factorize(n): primfac = [] d = 2 = -1 while d <= n: if n % d == 0: primfac.append(1) += 1 while (n % d) == 0: primfac[i] *= d n //= d d += 1 return primfac def crt(n, m): ans = 0 nfactors = primefactorizations[n] nfacts = nfactors mfactors = primefactorizations[m] mfacts = mfactors n = n + 1000000 m = m + 1000000 nfactor in nfacts: mfactor in mfacts: else: if is_power(nfactor, mfactor) true: if nfactor > mfactor: mfactors.remove(mfactor) m //= mfactor if mfactor > nfactor: nfactors.remove(nfactor) n //= nfactor if mfactor == nfactor: mfactors.remove(mfactor) m // mfactor else: pass print nfactors print mfactors primefactorizations = [] in range(1000000, 1005000): primefactorizations.append(factorize(i)) n in range(0, 4999): m in range(n+1, 5000): crt(n, m)
looking @ crt
function, see modify nfactors
, mfactors
lists while iterating on them forwards. not aware think iterate on copies. however, nfacts
reference same mutable list instance nfactors
, same goes m...
. real independent copies, do
nfacts = nfactors[:] mfacts = mfactors[:]
Comments
Post a Comment