Example #1
0
def prime_equivalences(bound):
    """
    Let x,y be positive integers, with prime factorizations
    x = p_1^a_1 * ... * p_n ^ a_n
    y = q_1^b_1 * ... * q_n ^ b_n
    """

    primecap = int(log(bound) **2 / log(10) ) + 10
    primes = primes_and_mask(primecap)[0]
    temp = bound
    max_primes = 0
    for i, p in enumerate(primes):
        temp /= p
        if not temp:
            max_primes = i
            break

    res = []
    state = [0 for i in xrange(max_primes)]
    def recur(pind, bound, exp_bound):
        if bound == 0: return
        if exp_bound == 0: return
        if pind >= max_primes: return
        for exp in xrange(1, exp_bound+1):
            state[pind] = exp
            new_bound = bound / primes[pind]**exp
            if new_bound <= 0: break
            res.append(copy(state))
            recur(pind+1, new_bound, exp)
        #cleanup
        state[pind] = 0
    recur(0, bound, 100)
    return res, primes[:max_primes]
Example #2
0
def solve_1(cap,mod=10**9+7):
 primes = primes_and_mask(cap)[0]
 R = [1 for i in xrange(cap+1)]
 N = [i**4+4 for i in xrange(cap+1)]

 sq = [0,0,0,0]
 for p in primes:
  if p == 2:
    for i in xrange(1,cap+1):
      mul = 1
      while N[i]%2==0:
       N[i]/=2
       mul*=2
      if mul>1:
       R[i] = (R[i]*(mul+1))%mod
    continue
  sq[0] = mod_sqrt(p-4,p)
  if not sq[0]:
   continue
  sq[2] = mod_sqrt(sq[0],p)
  sq[3] = mod_sqrt(p-sq[0],p)
  sq[0] = (p-sq[3])%p
  sq[1] = (p-sq[2])%p
 # print p,sq
  for q in xrange(0,cap+1,p):
    for r in sq:
      if r and r <= cap-q:
        mul=1
        while N[q+r]%p==0:
         mul *= p
         N[q+r]/=p
        if mul > 1:
         R[q+r] = (R[q+r]*(mul+1))%mod
 print "Completed seiving."
 c=0
 s = 0
 for i,r in enumerate(R):
  if i==0:
   continue
  n = N[i]
  if n ==1:
    s =  (s + r -i**4-4)%mod
    continue
  factors = shanks_factorize(n)
  for f in factors:
    if f>1:
     r = (r*(f**factors[f]+1))%mod
  if len(factors)>=2:
   c +=1
  s =  (s + r -i**4-4)%mod
 print s 
 print c
 return s
Example #3
0
def solve(n):
    primes = np.array(pe.primes_and_mask(n)[0], dtype = np.int64)
    pi = len(primes)
    #product of first k primes mod p, for each prime
    mod_prods = 2*np.ones(pi, dtype=np.int64)
    a_mods = np.ones(pi, dtype = np.int64)
    #a_0 is 0, I guess
    a = 1
    mask = primes == -1

    for i in xrange(1, pi):
        #we want to find the smallest k with k*p_1*...*p_i + A_i = t*p_(i+1) + (i+1)
        #solving this equation mod p_(i+1) for k yields the answer
        p = primes[i]
        k = ((i+1 - a_mods[i]) * pe.mod_inv(mod_prods[i], p)) % p
        a_mods[i:] = (a_mods[i:] + k*mod_prods[i:]) % primes[i:]
        mod_prods[i:] *= p
        mod_prods[i:] %= primes[i:]
        mask[a_mods==0] = True
    print np.sum(primes[mask])
Example #4
0
def solve(n, k, mod = 10**9+7):
    primes = pe.primes_and_mask(n)[0]
    pi = len(primes) + 1
    nstates = 2 ** (len(bin(pi-1))-2)
    nimber_counts = np.zeros(nstates, dtype = np.int64)
    mask = np.zeros(n, dtype = np.int64)
#    pcounts = np.cumsum(mask.astype(int))
    for i, p in enumerate(primes, 1):
        mask[p] = i
        for j in xrange(p*p, n, p):
            if mask[j]:
                mask[j] = min(mask[j], i)
            else:
                mask[j] = i
    print "Starting exponentiation."
    bcounts = np.bincount(mask)
    nimber_counts[2:len(bcounts)] = bcounts[2:]
    nimber_counts[1] = 1
    nimber_counts[0] = bcounts[1]
    nimber_counts = nimber_exp(k, nimber_counts, mod)

    print "Solution " + str(nimber_counts[0])
Example #5
0
first_power_primes = np.load("e565primes.npy")
for p in first_power_primes:
    if not p%2017 == 2016: print p
plist = [(p,p) for p in first_power_primes]
"""
for k in xrange(1, (n/d)/6):
    p = d*k*6-1
    if pe.MillerRabin(p): first_power_primes.append(p)
    p += 2*d
    if pe.MillerRabin(p): first_power_primes.append(p)
print len(first_power_primes)
np.save("e565primes",np.array(first_power_primes))
"""
print len(first_power_primes)
sq = pe.isqrt(n)
primes = pe.primes_and_mask(sq)[0]
#print plist[0]
max_power = int(np.log(n)/np.log(2))
powers = {}
for power in xrange(2, max_power):
    powers[power] = []
    for p in primes:
        exp = p**power
        if exp > n:
            break
#        if p%2017 == 2016 and po: continue
        if ((exp*p-1)/(p-1)) % 2017 == 0:
            plist.append((exp, p))
#            print plist[-1]

plist = sorted(plist)
Example #6
0
from proj_euler import primes_and_mask
from proj_euler import MillerRabin
import sys

primes, mask = primes_and_mask(10 ** 4)


def concat(a, b):
    return int(str(a) + str(b))


def slower_is_prime(n):
    global primes
    for p in primes:
        if p * p > n:
            return 1
        if not n % p:
            return 0
    return 1


prime_dicts = {p: set() for p in primes}

for p1 in primes:
    for p2 in primes:
        if MillerRabin(concat(p1, p2)) and MillerRabin(concat(p2, p1)):
            prime_dicts[p1].add(p2)
best_sum = 10 ** 20

for p1 in primes:
    for p2 in primes:
Example #7
0
from  proj_euler import primes_and_mask


cap = 10**9
t = 100
primes = primes_and_mask(t)[0]
print primes

def nHamming(minInd,maxNum):
  global primes
  if maxNum <= 1:
    return maxNum  
  s = 1
  i = minInd
  for p in primes[minInd:]:
    if p > maxNum:
      return s
    s += nHamming(i,maxNum/p)
    i += 1
  return s

print nHamming(0,cap)
Example #8
0
from proj_euler import primes_and_mask
from math import log
import numpy as np

n = 2*10**7
logs = np.zeros(n)
mods = np.ones(n,dtype=int)
mod = 10**9
primes = primes_and_mask(n)[0]

def carmichael(p,k):
 if p == 2:
  if k <=2:
   return 2**(k-1)
  else:
   return 2**(k-2)
 else:
  return (p-1)*p**(k-1)

for p in primes:
 lp = log(p)
 k = 1
 while True:
  d = carmichael(p,k)
  if d > n:
   break
  lg = k*lp
  for i in xrange(d,n,d):
   logs[i] += lp
   mods[i] = (mods[i]*p) % mod
  k += 1
Example #9
0
import proj_euler as pe
import numpy as np
cap = 2*10**9
primes,mask = pe.primes_and_mask(int(cap**.5))

def f_old(cap):
  global primes, mask
  sq = set()
  sqList = []
  for i in xrange(1,int(cap**.5)+1):
    sq.add(i*i)
    sqList.append(i*i)

  s1 = set()
  s2 = set()
  s3 = set()
  s7 = set()

  for i in sqList:
    for j in sqList:
      t1 = i+j
      if t1 > cap:
        break
      s1.add(t1)
      t2 = i + 2*j
      t3 = i + 3*j
      t7 = i + 7*j
      if t2 <= cap:
        s2.add(t2)
        if t3 <= cap:
          s3.add(t3)
Example #10
0
import proj_euler as pe

pcap = 2*10**5
d = 19
cap = 10**12
pow10 = [10**i for i in xrange(d+2)]
primes = pe.primes_and_mask(pcap)[0]

def prime_proof(t,st):
  global pow10
  digs = len(st) #number of digits
  for i in xrange(digs):
    for j in xrange(10):
      temp = t + (j-int(st[-i-1]))*pow10[i]
      if pe.MillerRabin(temp):
        return False
  return True


pp_squbes = []
for p in primes:
  if p > cap/8:
    break
  for q in primes:
    if q == p:
      continue
    t = p*p*q**3
    if t > cap:
      break
    st = str(t)
    if st.find("200") >= 0:
Example #11
0
import proj_euler as pe
import numpy as np

# cap = 100000000
cap = 1000000
s = 0
op = 0

primes, mask = pe.primes_and_mask(cap)

factorDict = {}
for p in primes:
    j = 2 * p
    while j <= cap:
        if mask[j - 1]:
            t = j
            e = 0
            while t % p == 0:
                t /= p
                e += 1
            if j not in factorDict:
                factorDict[j] = [(p, 2 * e)]
            else:
                factorDict[j].append((p, 2 * e))
        j += p

factorDict[3] = [(3, 2)]

nump = len(primes)
print "nump: " + str(nump)
Example #12
0
from proj_euler import primes_and_mask
import numpy as np

k = 20000
mod=1004535809
primes = np.array(primes_and_mask(5*10**5)[0][:k+1])
A1 = np.zeros(k+1,dtype=np.int64)
A1[1:] = primes[1:]-primes[:-1]
A1[0] = 1

def seq_mult(a,b,mod):
 '''
 Given two polynomials of degree at most n with coefficients given by a and b, numpy arrays.
 This function returns the first n coefficients of a*b, modulo mod.
 '''
 n=a.size
 if not n == b.size:
  raise ValueError("Input arrays must have the same shape in seq_mult.")
 res = np.zeros(n,dtype=np.int64)
 for i in xrange(n):
  res[i:] = np.remainder(res[i:] + b[i]*a[:n-i],mod)
 return res

t=k
accum = np.zeros(k+1,dtype=np.int64)
accum[0] = 1
temp = np.copy(A1)
#print temp, accum
while t:
 if t&1:
  accum = seq_mult(accum,temp,mod)
Example #13
0
import proj_euler as pe

N = 50
primes = pe.primes_and_mask(N)[0]

def comb_squarefree(n,k):
  global primes
  for p in primes:
    t = pe.prime_fact_ord(p,n)-pe.prime_fact_ord(p,n-k)-pe.prime_fact_ord(p,k)
    if t > 1:
      return 0
  return 1

s = set()
prev = [0 for i in xrange(N+1)]
curr = []
for i in xrange(N+1):
  curr = [1]
  for j in xrange(N):
   curr.append(prev[j]+prev[j+1])
   if curr[-1] and comb_squarefree(i,j+1):
     s.add(curr[-1])
  prev = curr

print sum(s)      
Example #14
0
from proj_euler import primes_and_mask
from math import log

primes = primes_and_mask(10**4)[0]

def is_counterexample(p,q):
  if p == q:
    return False	
  mod = (p-1)*(pow(q,p)-1) / (q-1)
  res = pow(p,q,mod)-1
  if not res:
    return True
  else:
   return False

exp_bound = 10000
for i,p in enumerate(primes):
 if p < exp_bound:
   if i%100==0:
     print "On %d" % i
   for q in primes:
     if is_counterexample(p,q):
       print "Counterexample found at %d,%d" % (p,q)
 else:
  break
Example #15
0
from proj_euler import primes_and_mask,isqrt,MillerRabin
from bisect import bisect_left
import sys

sys.setrecursionlimit(10**6)


primes = primes_and_mask(10**6)[0]

f = [0,1]
for i in xrange(43):
 f.append(f[-1]+f[-2])

def pi(n):
  pos = bisect_left(primes,n)
  return pos+1 if primes[pos] == n else pos

cache = {}
def phi(x, a):
  if (x, a) in cache:
    return cache[(x, a)]
  if a == 1:
    return (x + 1) // 2
  t = (x+1) // 2
  for i in xrange(1,a):
   t -= phi(x // primes[i], i)
#  t = phi(x, a-1) - phi(x // primes[a-1], a-1)
  cache[(x, a)] = t
  return t
def fpi(n):
 if n <= len(primes):
Example #16
0
import numpy as np
import proj_euler as pe

maxSum = 1548136
cap = 5000
mod = 10**16
primes,mask = pe.primes_and_mask(maxSum)

old = np.zeros(maxSum+1).astype(np.int64)
new = np.zeros(maxSum+1).astype(np.int64)

old[0] = 1
s = 0
for p in primes:
  if p > cap:
    break
  s += p
  for j in xrange(p):
    new[j] = old[j]
  for j in xrange(p,s+1):
    new[j] = (old[j] + old[j-p]) % mod
  
  temp = old
  old = new
  new = temp
res = 0

for p in primes:
  res = (res + old[p]) % mod

print res
Example #17
0
from CR_NEWTON_LAGRANGE import Lagrange_cr as chin
import proj_euler as pe

cap = 5000
lower = 1000
N = 10**18
K = 10**9

primes = pe.primes_and_mask(cap)[0][168:]
np=len(primes)
print np
s = 0

def binom(n,k,p):
  if k > n:
    return 0
  if not k:
    return 1
   
  if k < p:
    r = 1
    
    for i in xrange(k):
      r = ( r * pow(i+1,p-2,p) * (n-i))%p
    return r
  
  return (binom(n/p,k/p,p) * binom(n%p,k%p,p))%p

pc = {p:binom(N,K,p) for p in primes}

for i,p in enumerate(primes):
Example #18
0
import proj_euler as pe
import timeit
import numpy as np
from bisect import bisect_left
import sys

cap = 10**int(sys.argv[1])
mP = min(5*10**7,int(cap**(2./3)))
primes,mask = pe.primes_and_mask(mP)

NP =  len(primes)

print "NUMP " +str(NP)
print "PCAP " + str(mP) 

f = lambda n : n*(n+1) / 2 

s = f(cap)

def prods(prod,sign, startNum,primes,NP):
  global s,cap
  if prod > cap:
    return
  
  for i in xrange(startNum,NP):
    if primes[i] > cap/prod:
      break  
    s += sign * (prod*primes[i] * f(cap/(prod*primes[i])) - primes[i] * (cap/(prod*primes[i])))
    prods(prod*primes[i], -1*sign,i+1,primes,NP)
  return
  
Example #19
0
import proj_euler as pe
import numpy as np

primes= pe.primes_and_mask(25)[0]
cap = 10**8
cands = sorted([el for el in pe.HarshadGen(primes, cap, exact=False)])
print len(cands)
seen = {}
for i, el in enumerate(cands):
    for other in cands[i:]:
        if other > 1.1*el:
            break
        else:
            s = el*other
            reps = 1
            if s not in seen:
                seen[s] = reps
            else: seen[s] += reps

m_dict = {i:np.inf for i in xrange(2,101)}
for el in seen:
    if seen[el] > 100 or seen[el]==1: continue
    m_dict[seen[el]] = min(m_dict[seen[el]], el)
print m_dict
print sum([m_dict[i] for i in xrange(2,101)])
Example #20
0
from proj_euler import primes_and_mask
from math import log,floor
cap = 10**6+4
p1_cap = 10**6
primes = primes_and_mask(cap)[0]

l = log(10)
pow10 = [10**i for i in xrange(7)]
s = 0

for i,p in enumerate(primes):
  if p > p1_cap:
    break
  if p < 5:
    continue
  
  digits = int(floor(log(p)/l)) + 1
  p10 = pow10[digits]
  p2 = primes[i+1]
  n = p + p10 * (((p2-p) * pow(p10,p2-2,p2)) % p2)
#  print n,p,p2,p10
  s += n
print s
Example #21
0
def init(n):
 global pcap,primes,mask
 pcap = int(n**.5)+1
 primes,mask = primes_and_mask(pcap)