def S(N): primes = MakePrimeList(N) squareDivisors = rootGreatestSquareDivisorList(N) s = 0 for n, a in enumerate(primes): if isDigitPowTen(n): print n, a, s ap = a + 1 den = squareDivisors[ap] num = den + 1 while True: bp = ap * num // den cp = ap * num * num // (den * den) if cp > N: break if Miller_Rabin(bp - 1) and Miller_Rabin(cp - 1): s += a + bp + cp - 2 num += 1 #for b in primes[n+1:]: # if (b+1)*(b+1) >= (N+1)*(a+1): # break # c = (b+1)*(b+1) // (a+1) - 1 # if (a+1)*(c+1) == (b+1)*(b+1) and Miller_Rabin(c): # s += a + b + c return s
def Euler263(): primes = MakePrimeList(1000000) eps = [] base = 840 sexyTriples = 0 while len(eps) < 4: if (base//84) % 1000000 == 0: print('base = {:10} Sexy triples tested : {:6}'.format(base, sexyTriples)) for n in [base-20, base+20]: if (Miller_Rabin(n-9) and not Miller_Rabin(n-7) and not Miller_Rabin(n-5) and Miller_Rabin(n-3) and not Miller_Rabin(n-1) and not Miller_Rabin(n+1) and Miller_Rabin(n+3) and not Miller_Rabin(n+5) and not Miller_Rabin(n+7) and Miller_Rabin(n+9)): sexyTriples += 1 if (isPractical(n-8, primes) and isPractical(n-4, primes) and isPractical(n, primes) and isPractical(n+4, primes) and isPractical(n+8, primes)): eps.append(n) print('{0:10}\n\tSexy-Triple: {1:50}\n\tPracticals: {2:60}'.format(n, (n-9, n-3, n+3, n+9), (n-8, n-4, n, n+4, n+8))) base += 840 return sum(eps)
def solution(): Nmax = 10**10 kSet = set() r = int(Nmax**0.5) + 1 primes = MakePrimeList(int(r**0.5) + 10) squareParts = [1] * (r + 2) squareFreeParts = [x for x in range(r + 2)] for x in range(2, r + 2, 4): squareFreeParts[x] //= 2 for x in range(4, r + 2, 4): squareFreeParts[x] //= 4 for p in primes: for x in range(p * p, r + 2, p * p): while squareFreeParts[x] > 0 and squareFreeParts[x] % (p * p) == 0: squareFreeParts[x] //= p * p squareParts[x] *= p for m in range(1, r + 1): # k is at least m^2 g = gcd(4, m * (m + 1)) xx = squareParts[m] * squareParts[m + 1] y = squareFreeParts[m] * squareFreeParts[m + 1] b = 4 // g D = y * b for z, v in positivePell(D, 10000): if (z % 2 == 0 or z < 2 * m + 1): continue q = xx * y * v x = (z - 1) // 2 - m k = m * (x + m + 1) + q if k > Nmax: break kSet.add(k) kVec = list(kSet) kVec.sort() s = 0 for k in kVec: s += k return s
def makeOneSols(n): isOneSol = [True] * (n + 1) primes = [p for p in MakePrimeList(n) if p % 6 == 1 or p == 3] for p in primes: for x in range(p, n + 1, p): isOneSol[x] = False return [x for x in range(1, n + 1) if isOneSol[x]]
def twoSquares(self, n): # Get prime factors m = n primeFactorization = defaultdict(int) if self.N**2 < m: self.N = 2*self.N self.primes = MakePrimeList(self.N) for p in self.primes: if p*p > m: break while m%p == 0: primeFactorization[p] += 1 m //= p if m != 1: primeFactorization[m] += 1 # Calculate how many ways to write n as the sum of two squares a0 = primeFactorization[2] B = 1 for p in primeFactorization.keys(): if p%4 == 1: B *= primeFactorization[p] + 1 if p%4 == 3: if primeFactorization[p]%2 == 1: B = 0 break return B
def not2sRelatives(N): primes = MakePrimeList(N) relatives2 = defaultdict(bool) relatives2[2] = True count = 0 for p in primes: count += 1 if count % 100 == 0: print '%d/%d\t%d' % (count, len(primes), p) if p > 100 and str(p)[:2] == '10': continue visited = defaultdict(bool) shell = [p] while shell: new_shell = [] for q in shell: visited[q] = True if relatives2[q]: # q is 2's rel ==> p is 2's rel relatives2[p] = True new_shell = [] break conns = [x for x in getConnections(q) if x < p] conns = [x for x in conns if Miller_Rabin(x)] conns = [x for x in conns if not visited[x]] new_shell.extend(conns) shell = new_shell #print shell, visited[101] return [p for p in primes if not relatives2[p]]
def __init__(self, n, MOD): self.primes = MakePrimeList(n) self.n = n self.MOD = MOD self.calculateFactorials() self.calculateBinomials() self.calculateDivisors() self.sumDivisors()
class PrimeFactorization: primes = MakePrimeList(1000) def __init__(self, n): if PrimeFactorization.primes[-1] < intRoot(n): PrimeFactorization.primes = MakePrimeList(intRoot(n)) self.pf = defaultdict(int) for p in PrimeFactorization.primes: if p * p > n: break while n % p == 0: self.pf[p] += 1 n //= p if n > 1: self.pf[n] += 1 def __mul__(self, other): if isinstance(other, PrimeFactorization): rhs = other else: rhs = PrimeFactorization(other) ret = PrimeFactorization(1) for k in set(rhs.pf.keys()) | set(self.pf.keys()): exponent = self.pf[k] + rhs.pf[k] if exponent != 0: ret.pf[k] = exponent return ret def __rmul__(self, other): lhs = PrimeFactorization(other) return self * lhs def __div__(self, other): if isinstance(other, PrimeFactorization): rhs = other else: rhs = PrimeFactorization(other) nrhs = PrimeFactorization(1) for k in rhs.pf.keys(): nrhs.pf[k] = -rhs.pf[k] return self * nrhs def __rdiv__(self, other): lhs = PrimeFactorization(other) return lhs / self def __str__(self): if len(self.pf) == 0: return '1' keys = list(self.pf.keys()) keys.sort() strs = [ '{0}^{1}'.format(k, self.pf[k]) for k in keys if self.pf[k] != 0 ] return ' '.join(strs) def __repr__(self): return str(self)
def Euler315(): ps = MakePrimeList(2*10**7) ret = 0 n = bisect(ps,10**7) print ps[n-1],ps[n],ps[n+1],ps[-1] print ps[n:][0] for p in ps[n:]: ret += digitalRootTransDiff(p) return 2*ret
def __init__(self, N, talk=False): self.talk = talk self.N = N self.r = intRoot(N) self.primes = MakePrimeList(self.r) self.mobius = Mobius(self.r) self.isSquareFree = self.makeSquareFree(self.r) self.factCache = {} self.sfCache = {}
def Euler342b(N): ps = MakePrimeList(int(N**0.5) + 1) ret = 0 for n in xrange(2, N): if n % 10000 == 0: print n, ret if isCube(n * eulerPhi(n, ps)): ret += n return ret
def calcMu(self): primes = MakePrimeList(self.pMax) mu = [1] * (self.pMax + 1) for p in primes: for x in range(p, len(mu), p): mu[x] *= -1 for x in range(p * p, len(mu), p * p): mu[x] = 0 return mu
def makeMu(l): primes = MakePrimeList(l) mu = [1] * (l + 1) for p in primes: for x in range(p, l + 1, p): mu[x] *= -1 for xx in range(p * p, l + 1, p * p): mu[xx] = 0 return mu
def C(n, color='r', plo=False): ps = MakePrimeList(n) print 'Primes Calculated' mu = list(ones(n + 1)) for p in ps: for x in range(p, n + 1, p): mu[x] *= -1 for x in range(p * p, n + 1, p * p): mu[x] = 0 print 'Mobius Function Calculated' P = zeros(n + 1, dtype=int) N = 0 * P for i in range(1, n + 1): P[i] = P[i - 1] + (mu[i] == 1) N[i] = N[i - 1] + (mu[i] == -1) PmN = 100 * P - 99 * N NmP = 100 * N - 99 * P if plo: figure(2) plot(PmN, 'b') plot(NmP, 'g') plot((PmN + NmP) / 2., 'r') ans = 0 alistb = [] blistb = [] alistg = [] blistg = [] alistr = [] blistr = [] for a in range(1, n + 1): for b in range(a, n + 1): #NN = N[b] - N[a-1] #PP = P[b] - P[a-1] #if 99*NN <= 100*PP and 99*PP <= 100*NN: if PmN[b] >= PmN[a - 1]: alistb.append(a) blistb.append(b + 0.3) if NmP[b] >= NmP[a - 1]: #pass alistg.append(a + 0.3) blistg.append(b) if PmN[b] >= PmN[a - 1] and NmP[b] >= NmP[a - 1]: alistr.append(a) blistr.append(b) ans += 1 if plo: figure(1) plot(alistb, blistb, 'ob') plot(alistg, blistg, 'og') plot(alistr, blistr, 'or') blue = countCriterion(PmN) print 'Blue Calculated' green = countCriterion(NmP) print 'Green Calculated' return blue + green - n * (n + 1) / 2
def __init__(self, n): if PrimeFactorization.primes[-1] < intRoot(n): PrimeFactorization.primes = MakePrimeList(intRoot(n)) self.pf = defaultdict(int) for p in PrimeFactorization.primes: if p * p > n: break while n % p == 0: self.pf[p] += 1 n //= p if n > 1: self.pf[n] += 1
def makeSumPhi(l): primes = MakePrimeList(l) phi = [x for x in range(l + 1)] for p in primes: for x in range(p, l + 1, p): phi[x] *= (p - 1) phi[x] //= p # Summatory phi starting from 2 for x in range(3, l + 1): phi[x] += phi[x - 1] return phi
def Euler233(N): ps = MakePrimeList(max(17, N / (5**3 * 13**2))) qs = [q for q in ps if q % 4 == 1] pNums, pSums = pNumsSums(qs, N / (5**3 * 13 * 2 * 17)) patterns = [(52, 0, 0), (17, 1, 0), (10, 2, 0), (7, 3, 0), (3, 2, 1)] nums420sum = 0 for b in patterns: for qNum in qNumGen(qs, b, N): ix = bisect(pNums, N / qNum) if ix > 0: nums420sum += qNum * pSums[ix - 1] return nums420sum
def Euler245(N): primes = MakePrimeList(10**7) solutions = set() for sf, sfphi in squareFreeGen(N, primes, 1): if sfphi+1 == sf: continue if (sf - 1) % (sf - sfphi) == 0: solutions.add((sf,sfphi)) sols = list(solutions) sols.sort() for s in sols: print s return sum(s[0] for s in solutions)
def _updatePrimeList(self, N): if N <= self.N: return self.primes = MakePrimeList(N) self.squareFreeNumbers = list(range(N + 1)) self.squareFreePrimeList = defaultdict(list) for p in self.primes: pp = p * p if p > N: break for x in range(p, N + 1, p): while self.squareFreeNumbers[x] % pp == 0: self.squareFreeNumbers[x] /= pp if self.squareFreeNumbers[x] % p == 0: self.squareFreePrimeList[x].append(p)
def squareFreeNumbers(N): primes = MakePrimeList(N) sf = [True] * (N + 1) numPrime = [0] * (N + 1) last = 1 for p in primes: if last // 100000 != p // 100000: print p for pp in range(p, N + 1, p): numPrime[pp] += 1 for pp in range(p * p, N + 1, p * p): sf[pp] = False last = p return [(x, numPrime[x]) for x in range(1, N + 1) if sf[x]]
def Euler437(N): ps = MakePrimeList(N) ret = 0 count = 0 for p in ps[1:]: # ps[1:] excludes 2, the case where 2^-1 does not exist if isQuadResidue(5 % p, p): r = tonelliShanks(5 % p, p) inv2 = pow(2, p - 2, p) x1 = (inv2 * (1 + r)) % p x2 = (inv2 * (1 - r)) % p if isPrimitiveRoot(x1, x2, p, ps): ret += p count += 1 return count, ret
def S(n): primes = MakePrimeList(n) s = [0]*(n+1) for p in primes: pp = p e = 1 while pp <= n: sPrime = sPrimePower(p,e) for x in range(pp,n+1,pp): if sPrime > s[x]: s[x] = sPrime pp *= p e += 1 print s[:min(len(s), 20)] return sum(s)
def F(n, d): MOD = 10**16 + 61 # Count digits numDigs = 0 dd = d # have to preserve d while dd > 0: numDigs += 1 dd //= 10 # Set up dynamic programming pow10 = 10**numDigs if d == 0: pow10 = 10 factors = [0] * pow10 factors[1] = 1 primes = MakePrimeList(n) # Dynamic programing loop pLast = 1 for p in primes: if p // 10000 > pLast // 10000: print p, factors[:10] print p, newFactors = [0] * pow10 exponent = 0 pp = p while pp <= n: exponent += n // pp pp *= p # Exponent is ~10^6 for p=2 # Need to decouple the exponent loop from the factor loop ppCount = [0] * pow10 for e in range(exponent + 1): ppCount[pow(p, e, pow10)] += 1 print ppCount[:10], nulls = 0 for pp in range(pow10): if ppCount[pp] == 0: nulls += 1 continue for i in range(pow10): newFactors[(i * pp) % pow10] += ppCount[pp] * factors[i] print pow10 - nulls factors = newFactors for i in range(pow10): factors[i] %= MOD pLast = p return factors[d]
def g(N): ps = MakePrimeList(int((2*N+2)**(0.5))) n = 9 n_last = 9 while n <= N: #print n z = 2*n-1 if Miller_Rabin(z): k = (z-3)/2 for p in ps: if z%p == 0: k = (p-3)/2 break n_last = n n += k + 1 return 2*n_last + N
def sumLargestIdempotents(N): primes = MakePrimeList(N) phi = EulerPhi(N) p_facts = primeFactorsLists(N,primes) ret = 0 for x in xrange(1,N+1): if x % 10000 == 0: print 'Sum:\t%d/%d Complete\t\t%d'%(x,N,ret) idempotents = [] for r in range(len(p_facts[x])+1): for c in combinations(p_facts[x],r): p = int(prod(c)) q = x / p idempotents.append((p*pow(p,int(phi[q])-1,q))%x) #print x,phi[x], max(idempotents), idempotents ret += int(max(idempotents)) return ret
def primeFactorizations(n): ''' Create a list of prime factorizations, where each prime factorizeation is a dictionary with primes as keys and exponents as values ''' primes = MakePrimeList(n+1) fact = [defaultdict(int) for _ in range(n+1)] for p in primes: pp = p while pp <= n: for x in range(pp,n+1,pp): fact[x][p] += 1 pp *= p return fact
def P(n): primes = MakePrimeList(n) isPrime = [False for x in range(n+1)] for p in primes: isPrime[p] = True primePi = calcPrimePi(n, primes) seq = piSequence(n, primePi) #print seq kMax = len(seq) pnk = [0]*(kMax+1) pnk[1] = 1 cache = {} for pix in range(len(primes)): p = primes[pix] pNext = n+1 if pix < len(primes)-1: pNext = primes[pix+1] pnkSeq = pNK(p, primePi, isPrime, cache, True) d = pNext - p - 1 for k in range(len(pnkSeq)): pnk[k] += pnkSeq[k] pnk[k+1] += d * pnkSeq[k] #print p, pnkSeq, pnk #for x in range(n,0,-1): # pnkSeq = pNK(x, primePi, isPrime, cache, True) # #print x, pnkSeq # for k in range(len(pnkSeq)): # pnk[k] += pnkSeq[k] if pix%100000 == 0: print pix, p, pnkSeq #print pnk pnk[0] -= len(primes) pnk[1] -= n pnk[1] += len(primes) #print pnk pr, MOD = 1, 10**9+7 for x in pnk: if x != 0: pr *= x pr %= MOD return pr
def Euler500(N, MOD=500500507): # Num divisors = 2^N ps = MakePrimeList(N * sp.log(N) * 2)[:N] a = [0] * N ans = 1 # least_ix[y] is the smallest index in a[:] which has value y least_ix = [0 ] * int(2 + sp.log(1 + sp.log(ps[-1]) / sp.log(2)) / sp.log(2)) for x in xrange(N): m = [(ps[least_ix[y]]**(2**y), y) for y in range(sum(z != 0 for z in least_ix) + 1)] m.sort() #if x%1000 == 0: # print x, least_ix, [z[0] for z in m] multiplier, y = m[ 0] # y is the index in least_ix with the smallest multiplier least_ix[y] += 1 ans *= multiplier ans %= MOD return ans
def __init__(self, kMax, N, MOD): self.kMax = kMax self.N = N self.R = intRoot(N) self.MOD = MOD self.primes = MakePrimeList(intRoot(N)) self.squareFreeParts = self.calculateSquareFreeParts() self.sCache = self.initializeSCache() self.partialSumCache = {} self.chooseCache = {} self.calculateBernoulli() self.calculateFaulhaber() self.sumOverPrimesCache = self.initializeSumOverPrimesCache() self.partialSumOverPrimesCache = {} self.psCalled = 0 self.psCacheHits = 0 self.psopCalled = 0
def S(n, pMOD): r = int(n**0.5) + 1 primes = MakePrimeList(r) eligiblePrimePowers = [] for p in primes: pp = 1 pS = 0 while pp <= n: pS += pp if pS % pMOD == 0: eligiblePrimePowers.append((pp, p)) pp *= p # Check even multiples of pMOD start = (r // (2 * pMOD) + 1) * (2 * pMOD) for x in range(start, n + 1, 2 * pMOD): if Miller_Rabin(x - 1): eligiblePrimePowers.append((x - 1, x - 1)) eligiblePrimePowers.sort() print len(eligiblePrimePowers)