def nth_prime(n): assert n > 0 bound = max([1, int(math.log(n) * n)]) primes = sieve(bound) while len(primes) < n: bound *= 2 primes = sieve(bound) return primes[n - 1]
def test3(): s = sieve.sieve() i = iter(s) for x in sieve.sieve(): if x > 151: break assert x == 157 print x
def test2(): s = sieve.sieve() i = iter(s) for x in sieve.sieve(): if x > 10: break assert x == 11 print x
def agen(i, k=3): primes = sieve(k) if k not in sieve(k + 1): return while True: yield int(i) if i <= 1: break for p in primes: if 0 == i % p: i = i / p break else: i = k * i + 1
def factorize(p): """Returns a list of the prime factors of p. If a number is a factor multiple times (such as with squares or cubes), it will be included in the factor list once for each multiplication. If p is itself prime, returns a list consisting of one element, p. Args: p: integer, the number for which to find prime factors. Returns: A list of the prime factors for p, or an empty list if p < 2. Raises: ValueError: p is < 2. """ primes = sieve(p) # If p is prime, it should be at the end of the list and will have # no other factors if primes[-1] == p: return [p] factors = [] for prime in primes: if p == 1: break # Use while instead of if for squares, cubes, etc while p % prime == 0: factors.append(prime) p /= prime return factors
def test1(): s = sieve.sieve() i = iter(s) n = i.next() print n assert n == 3 print "***Test 1 passed!***"
def test3(): s = sieve.sieve() i = iter(s) for x in range(8): i.next() assert i.next() == 29
def test1(): s = sieve.sieve() #make a sieve object from file sieve i = iter(s) #make iterator val=i.next() #run iterator once, put value in val assert val == 3 #check if value is 3. if not 3, fail. print "Value should be 3, actual value is:" print val
def test3(): sieveInstance = sieve.sieve() i = iter(sieveInstance) i.next() i.next() assert i.next() == 7 print "Test 3 Passes"
def primes2(pf, n): if pf <= 0: raise ValueError elif n <= 2**pf: return [] P = sieve(n) if pf == 1: return P powP = [P] func = lambda p: (lambda x: (powP[p][x] * P[x] < n)) for p in range(pf): tmpP = binary_takewhile(powP[p], func(p)) powP.append(tmpP * P[:len(tmpP)]) del tmpP T = np.zeros(n, dtype=np.uint8) for Ps in powP: for p in Ps: T[p::p] += 1 del powP return np.where(T == pf)[0].astype(np.uint64)
def test3(): "3 is a bigger number than 2 or 1, and thats a fact" s = sieve.sieve() i = iter(s) i.next() i.next() assert i.next() == 7
def test1(): s = sieve.sieve() #create an object of type sieve i = iter(s) #create an interator for the object sieve #Check if next value is equal to 3 #Error would occur if the value is not equal to 3 assert i.next() == 3
def test2(): s = sieve.sieve() i = iter(s) for x in range(4): i.next() assert i.next() == 13
def createAlgsList(self): # First we populate the list of algorithms with those created # extending GeoAlgorithm directly (those that execute GDAL # using the console) self.preloadedAlgs = [nearblack(), information(), warp(), translate(), rgb2pct(), pct2rgb(), merge(), buildvrt(), polygonize(), gdaladdo(), ClipByExtent(), ClipByMask(), contour(), rasterize(), proximity(), sieve(), fillnodata(), ExtractProjection(), gdal2xyz(), hillshade(), slope(), aspect(), tri(), tpi(), roughness(), ColorRelief(), GridInvDist(), GridAverage(), GridNearest(), GridDataMetrics(), gdaltindex(), gdalcalc(), rasterize_over(), # ----- OGR tools ----- OgrInfo(), Ogr2Ogr(), Ogr2OgrClip(), Ogr2OgrClipExtent(), Ogr2OgrToPostGis(), Ogr2OgrToPostGisList(), Ogr2OgrPointsOnLines(), Ogr2OgrBuffer(), Ogr2OgrDissolve(), Ogr2OgrOneSideBuffer(), Ogr2OgrTableToPostGisList(), OgrSql(), ] # And then we add those that are created as python scripts folder = self.scriptsFolder() if os.path.exists(folder): for descriptionFile in os.listdir(folder): if descriptionFile.endswith('py'): try: fullpath = os.path.join(self.scriptsFolder(), descriptionFile) alg = GdalScriptAlgorithm(fullpath) self.preloadedAlgs.append(alg) except WrongScriptException as e: ProcessingLog.addToLog(ProcessingLog.LOG_ERROR, e.msg)
def test2(): s = sieve.sieve() i = iter(s) print i.next() print i.next() assert i.next() == 7 print "***Test 2 passed!***"
def test(r): print 'Running test for', r, 'items' for n, i in zip(range(r), sieve.sieve()): print i print '\n'
def createAlgsList(self): # First we populate the list of algorithms with those created # extending GeoAlgorithm directly (those that execute GDAL # using the console) self.preloadedAlgs = [nearblack(), information(), warp(), translate(), rgb2pct(), pct2rgb(), merge(), polygonize(), gdaladdo(), ClipByExtent(), ClipByMask(), contour(), rasterize(), proximity(), sieve(), fillnodata(), ExtractProjection(), gdal2xyz(), hillshade(), slope(), aspect(), tri(), tpi(), roughness(), ColorRelief(), GridInvDist(), GridAverage(), GridNearest(), GridDataMetrics(), # ----- OGR tools ----- OgrInfo(), Ogr2Ogr(), OgrSql(), ] # And then we add those that are created as python scripts folder = self.scriptsFolder() if os.path.exists(folder): for descriptionFile in os.listdir(folder): if descriptionFile.endswith('py'): try: fullpath = os.path.join(self.scriptsFolder(), descriptionFile) alg = GdalScriptAlgorithm(fullpath) self.preloadedAlgs.append(alg) except WrongScriptException, e: ProcessingLog.addToLog(ProcessingLog.LOG_ERROR, e.msg)
def primes4(pf, n): if pf <= 0: raise ValueError elif n <= 2**pf: return [] P = sieve(-(-n >> (pf - 1))) if pf == 1: return P PH = [0] * (pf - 1) sup = pow(n, 1 / pf) pwpf = 2**pf T = np.zeros(n - pwpf, dtype=np.bool) func = lambda x: (Pprod * P[x + index] < n) while P[PH[0]] < sup: index = PH[-1] Pprod = np.prod(P[PH]) if Pprod * P[index] < n: T[(binary_takewhile(P[index:], func) * Pprod) - pwpf] = True PH[-1] += 1 else: for i in range(-2, -pf - 1, -1): if PH[i] != index: PH[i:] = [PH[i] + 1] * (-i) break del P return np.add(np.nonzero(T)[0].astype(np.uint64), np.uint64(2**pf))
def test3(): "This one is impossibly difficult to understand" # psych s = sieve.sieve() i = iter(s) i.next() i.next() assert i.next() == 7
def test_sieve_200(self): expected = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199 ] actual = sieve(200) self.assertEqual(expected, actual)
def test2(): s = sieve.sieve() i = iter(s) for x in range(3): i.next() assert i.next() == 11 # the fifth prime number should be 11
def test3(): s = sieve.sieve() # make a sieve object from file sieve i = iter(s) # make iterator val = i.next() # run iterator once, put value in val assert val != 2 # check if value not 2 print "Value should not be 2, actual value is:" print val
def test3(): primes_list = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] ctr = 1 for n, i in zip(sieve.sieve(), primes_list): if ctr == 11: break assert n == i ctr += 1
def prime_factors(n): candidates = sieve(n + 1) factors = [] for c in candidates: while n % c == 0: factors.append(c) n /= c return factors
def test2(): sve = sieve.sieve() i = iter(sve) nxt = i.next() print nxt nxt = i.next() print nxt assert nxt == 5
def test2(): s = sieve.sieve() # create an object of type sieve s.next() # move to the next prime number (3) # Check if next value is equal to 5 # Error would occur if the value is not equal to 5 assert s.next() == 5
def test2(): s = sieve.sieve() #create an object of type sieve i = iter(s) #create an interator for the object sieve i.next() #move to the next value of iterator 3 #Check if next value is equal to 5 #Error would occur if the value is not equal to 5 assert i.next() == 5
def test3(): s = sieve.sieve() i = iter(s) for n in range(13): i.next() assert i.next() == 47
def test2(): s = sieve.sieve() i = iter(s) for n in range(10): i.next() assert i.next() == 37
def test3(): s = sieve.sieve() i = iter(s) for c in range(10): print i.next() assert i.next() == 37 print "***Test 3 passed!***"
def prime_factors(n): primes = sieve(math.ceil(math.sqrt(n))) result = [] for p in primes: while n % p == 0: result.append(p) n /= p if n > 1: result.append(n) return result
def prime_factors(n): '''Find the prime factors of N''' factors = [] while n > 1: for p in sieve(n): if n % p == 0 or n == p: factors.append(p) n /= p break return factors
def createAlgsList(self): # First we populate the list of algorithms with those created # extending GeoAlgorithm directly (those that execute GDAL # using the console) self.preloadedAlgs = [ nearblack(), information(), warp(), translate(), rgb2pct(), pct2rgb(), merge(), buildvrt(), polygonize(), gdaladdo(), ClipByExtent(), ClipByMask(), contour(), rasterize(), proximity(), sieve(), fillnodata(), ExtractProjection(), gdal2xyz(), hillshade(), slope(), aspect(), tri(), tpi(), roughness(), ColorRelief(), GridInvDist(), GridAverage(), GridNearest(), GridDataMetrics(), gdaltindex(), gdalcalc(), rasterize_over(), retile(), gdal2tiles(), # ----- OGR tools ----- OgrInfo(), Ogr2Ogr(), Ogr2OgrClip(), Ogr2OgrClipExtent(), Ogr2OgrToPostGis(), Ogr2OgrToPostGisList(), Ogr2OgrPointsOnLines(), Ogr2OgrBuffer(), Ogr2OgrDissolve(), Ogr2OgrOneSideBuffer(), Ogr2OgrTableToPostGisList(), OgrSql(), ]
def main(n=1000000): sieve_list=sieve(n) count=11 primes=[] start=10 while count!=0 or start>n: if isTruncatableprime(start,sieve_list): primes.append(start) count-=1 start+=1 return primes
def main(n): oddities=[] prime_sieve=sieve(n) odd_sieve=gen_odd_composites(n,prime_sieve) for odd in odd_sieve: count=0 for prime in suitable_primes(odd ,prime_sieve): if isPerfectSquare((odd-prime)/2): count+=1 if count==0: oddities.append(odd) return oddities
def p_69(): max_n_phi = 0 n_max = 0 M = 10**6 cached_primes = sieve(M + 1) for n in xrange(2, M): n_phi = float(n)/totient(n, cached_primes) if n_phi > max_n_phi: max_n_phi = n_phi n_max = n print n_max, max_n_phi
def prime_factors(number): primes = sieve.sieve(number) factors = [] for prime in primes: if number in primes and number not in factors: factors.append(number) break if number % prime == 0: factors.append(prime) while number % prime == 0: number = number / prime return factors
def prime_factors(num): primes = sieve(num) index = 0 prime_factor = [] number_check = num while index != len(primes) and number_check != 1: prime_num = primes[index] if number_check % prime_num == 0: prime_factor.append(prime_num) number_check /= prime_num else: index += 1 return prime_factor
def test_five(): assert sieve(1000) == [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997 ]
def test_primes(self): expected = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997] self.assertEqual(expected, sieve(1000))
def pb35(): primes = set(sieve(10**6)) circular_count = 0 for p in primes: circular = True for r in number_rotations(p): if r not in primes: circular = False break if circular: circular_count+=1 print circular_count
def prime_factors(num): primes = sieve(num) prime_factors_list = [] for prime in primes: while num % prime == 0: prime_factors_list.append(prime) num = num // prime if num in primes: prime_factors_list.append(num) break else: continue prime_factors_list.sort() return prime_factors_list
def primes3_2(pf, n): if pf <= 0: raise ValueError elif n <= 2**pf: return [] P = sieve(-(-n >> (pf-1))) # nを2**(pf-1)で割って小数点以下切り上げ if pf == 1: return P PF = [] appendPF = PF.append func1 = lambda x: (P[x]**2 < -(-n >> (pf-2))) func2 = lambda x: (P[x]*p < -(-n >> (pf-2))) high = len(P) for j, p in enumerate(binary_takewhile(P, func1)): high = upper_bound(j, high, func2) appendPF(P[j:high] * p) func1 = lambda x: (PF[x][0]*P[x] < sup) func2 = lambda x: (PF[j][x]*p < sup) func3 = lambda x: (PF[x][0]*p < sup) func4 = lambda x: (S[x]*p < sup) high1 = len(PF) for i in range(3, pf+1): sup = -(-n >> (pf-i)) high1 = upper_bound(0, high1, func1) high3 = len(PF) for j, p in enumerate(P[:high1]): PF[j] = [binary_takewhile(PF[j], func2) * p] high3 = upper_bound(j+1, high3, func3) for S in PF[j+1:high3]: PF[j].append(binary_takewhile(S, func4) * p) PF[j] = np.concatenate(PF[j]) PF[j].sort() PF = PF[:high1].copy() del P PF = np.concatenate(PF) PF.sort() return PF
def primes3(pf, n): if pf <= 0: raise ValueError elif n <= 2**pf: return [] P = sieve(-(-n >> (pf - 1))) # 小数点以下切り上げ if pf == 1: return P PF = P.copy() func = lambda x: (PF[x] * p < -(-n >> (pf - i))) for i in range(2, pf + 1): ip = 2**i T = np.zeros(n - ip, dtype=np.bool) for p in P: T[(binary_takewhile(PF, func) * p) - ip] = True PF = np.add(np.nonzero(T)[0].astype(np.uint64), np.uint64(ip)) del T return PF
def primes4_2(pf, n): if pf <= 0: raise ValueError elif n <= 2**pf: return [] P = sieve(-(-n >> (pf-1))) if pf == 1: return P PH = [0] * (pf-1) PF = [] appendPF = PF.append npprod = np.prod high = len(P) func = lambda x: (Pprod*P[x] < n) while True: index = PH[-1] Pprod = npprod(P[PH]) if Pprod * P[index] < n: high = upper_bound(index, high, func) appendPF(P[index:high] * Pprod) PH[-1] += 1 else: for i in range(-2, -pf, -1): if PH[i] != index: PH[i:] = [PH[i] + 1] * (-i) high = len(P) break else: break del P PF = np.concatenate(PF) PF.sort() return PF
def quadSieve(n): factor = 1 upperSieveBound = 50 while factor == 1 or factor == n: upperSieveBound *= 2 sieveResult = sieve.sieve(n, upperSieveBound) smoothNumbers = sieveResult[0] primes = sieveResult[1] matrix = [] for numTup in smoothNumbers: expVec = [i % 2 for i in numTup[2]] matrix.append(expVec) if len(matrix) == 0: continue solutions = linearSolverMod2.solve(matrix) for solution in solutions: sieveExpVec = [0] * len(primes) originalSquare = 1 for index in solution: sieveExpVec = [ x + y for x, y in zip(sieveExpVec, smoothNumbers[index][2]) ] originalSquare *= smoothNumbers[index][0] for i in range(len(sieveExpVec)): sieveExpVec[i] //= 2 sieveVal = 1 for i in range(len(primes)): sieveVal *= pow(primes[i], sieveExpVec[i]) factor = gcd(abs(originalSquare - sieveVal), n) return {factor, n // factor}
def test_a_few_primes(self): expected = [2, 3, 5, 7] self.assertEqual(expected, sieve(10))
def main(): print(sieve(200000)[10001])
from sieve import sieve from itertools import takewhile # project Euler #10 primes = sieve(5000000) if primes[-1] < 2000000: raise Exception("too small: " + str(primes[-1])) result = sum(takewhile(lambda x: x < 2000000, primes)) print(result)
# -*- coding: utf-8 -*- """ Created on Wed Jul 02 11:22:19 2014 @author: Milad """ import sieve m = sieve.sieve(9999) n = sieve.sieve(1000) l = [x for x in m if x not in n] d = {} for i in l: d[i] = "".join(sorted([x for x in str(i)])) p = {} for k, v in d.iteritems(): for l, w in d.iteritems(): if v == w and k != l: if v in p.keys(): p[v].append(l) p[v] = list(set(p[v])) else: p[v] = [k, l] for k, v in p.iteritems(): v = sorted(v) for i in range(len(v) - 2):
def test_pos(self): """Tests filtering of positive even numbers""" self.assertEqual(sieve(POS, 2), [1, 3, 5, 7, 9])
def test_sieve(self): self.assertEqual(sieve(10), [1,2,3,5,7,9])
def test_no_primes_under_two(self): self.assertEqual(sieve(1), [])
def test_limit_is_prime(self): self.assertEqual(sieve(13), [2, 3, 5, 7, 11, 13])
def test_find_primes_up_to_10(self): self.assertEqual(sieve(10), [2, 3, 5, 7])
def test_find_first_prime(self): self.assertEqual(sieve(2), [2])
def test_prime_limit(self): expected = [2, 3, 5, 7] self.assertEqual(expected, sieve(7))
import sieve limit = 1000000 primes = sieve.sieve(limit) # Create a list of consecutive sums of all primes up to one million consec = [0] for i in range(2, len(primes)): if primes[i] == 1: # it is a prime number temp = i + consec[-1] if temp > limit * 10: break consec.append(temp) # consec = consec[1:] # Remove zero from the start print(consec) # Index position in consec tells us how many primes are used to get that consec sum # If want a consec sum from a starting position other than i = 0, then need to subtract the value # preceeding the start position # Adopt a method that works for lim = 100, must return 41 with 6 primes in the sum answer = 0 max_consec = 0 for i in range(len(consec) - 1): for j in range(i + 1, len(consec)): consec_sum = consec[j] - consec[i] if consec_sum >= limit: break if primes[consec_sum] == 1: length = j - i if length > max_consec: max_consec = length
import sieve # Composites in the list are marked as zero primes = sieve.sieve(1000000) # Main body of the problem, find how to break n into a prime and remainder # The remainder must be even, otherwise cannot be 2*square def check_conjecture(n): i = 1 while 2 * i * i + 2 < n: square = i * i if primes[n - 2 * square] == 1: # is prime that conjecture true return True i += 1 return False # Go over all odd composites for i in range(9, len(primes), 2): if primes[i] == 1: # not composite, skip continue if check_conjecture(i) == False: print("\nAnswer: ", i) break