示例#1
0
def S(N):
    Ms = set()
    for p in sieve.primerange(1, sqrt(N) + 1):
        for q in sieve.primerange(p + 1, N / p + 1):
            Ms.add(M(p, q, N))

    return sum(Ms)
示例#2
0
def euler087():
    result = set()
    limit = 50000000
    for p1 in sieve.primerange(2, limit**(1/2)):
        for p2 in sieve.primerange(2, limit**(1/3)):
            for p3 in sieve.primerange(2, limit**(1/4)):
                current = p1*p1 + p2*p2*p2 + p3*p3*p3*p3
                if current < limit:
                    result.add(current)
    print(len(result))
示例#3
0
def euler70():
    result = 1
    min_ratio = 2
    limit = 10000000
    lowerbound, upperbound = int(0.7 * (limit)**0.5), int(1.3 * (limit)**0.5)
    for p in sieve.primerange(lowerbound, upperbound):
        for q in sieve.primerange(p + 1, upperbound):
            n = p * q
            if n > limit:
                break
            phi = (p - 1) * (q - 1)
            ratio = n / phi
            if is_permutation(n, int(phi)) and min_ratio > ratio:
                result, min_ratio = n, ratio
    print(result)
示例#4
0
def qsieve(number):
        primelimit = 1000
        cores = 1
        primes = [p for p in sieve.primerange(2, primelimit)]
        factor_base = get_factor_base(number, primes)
        xs,ys = generate_smooth(number, factor_base)
        exponents = [generate_exponent_vector_m(y, factor_base, 2) for y in ys] # makes me miss haskell
        sols = SparseMatrix(exponents).transpose().nullspace()
        sol_found = False
        for sol in sols:
                a = 1
                b = 1
                z = sol.transpose()
                for i,x in enumerate(z):
                        if 1 == (x % 2):
                                a *= xs[i]
                                b *= ys[i]
                if (a ** 2 % number == b % number):
                        f1 = gcd(a + int(math.sqrt(b)),number)
                        if f1 == 1:
                                f1 = gcd(a - int(math.sqrt(b)),number)
                        f2 = number // f1
                        if 1 not in [f1,f2]: # if the trivial solution hasn't been found:
                                print("%d, %d %d" % (number, f1, f2))
                                return True
        print("No solution found for", number)
        return False
示例#5
0
def euler49():
    for p in sieve.primerange(1488, 9999):
        for i in range(1, 9999 - p):
            if is_permutation(p, p + i) and is_permutation(
                    p, p + 2 * i) and isprime(p + i) and isprime(p + 2 * i):
                print(str(p) + str(p + i) + str(p + 2 * i))
                return
示例#6
0
def GenerateCPrimeSet(limit):
    solSet = set()
    for i in sieve.primerange(1, limit):
        if i not in solSet:
            if CircularCheck(i):
                solSet.update(RotateNumSet(i))
    return solSet
示例#7
0
def GenerateCPrimeSet(limit):
	solSet = set()
	for i in sieve.primerange(1,limit):
		if i not in solSet:
			if CircularCheck(i):
				solSet.update(RotateNumSet(i))
	return solSet
示例#8
0
def number_of_devisors(n):
    if n == 1:
        return 1

    # nr_div = 2 # 1 and p.
    # x = 2
    # while x < p/x:
    #     if p % x == 0:
    #         nr_div += 2 # x and p/x
    #     x += 1

    should_print = False
    if n < 10:
        should_print = True

    nr_div = 1
    for p in sieve.primerange(2, n + 1):
        if p * p > n:
            nr_div *= 2
            break

        exponent = 0
        while n % p == 0:
            exponent += 1
            n = n // p

        if exponent > 0:
            nr_div *= exponent + 1

        if n == 1:
            break

    return nr_div
示例#9
0
文件: qs.py 项目: gvvynplaine/sympy
def _generate_factor_base(prime_bound, n):
    """Generate `factor_base` for Quadratic Sieve. The `factor_base`
    consists of all the the points whose ``legendre_symbol(n, p) == 1``
    and ``p < num_primes``. Along with the prime `factor_base` also stores
    natural logarithm of prime and the residue n modulo p.
    It also returns the of primes numbers in the `factor_base` which are
    close to 1000 and 5000.

    Parameters:
    ===========

    prime_bound : upper prime bound of the factor_base
    n : integer to be factored
    """
    from sympy import sieve
    factor_base = []
    idx_1000, idx_5000 = None, None
    for prime in sieve.primerange(1, prime_bound):
        if pow(n, (prime - 1) // 2, prime) == 1:
            if prime > 1000 and idx_1000 is None:
                idx_1000 = len(factor_base) - 1
            if prime > 5000 and idx_5000 is None:
                idx_5000 = len(factor_base) - 1
            residue = _sqrt_mod_prime_power(n, prime, 1)[0]
            log_p = round(log(prime) * 2**10)
            factor_base.append(FactorBaseElem(prime, residue, log_p))
    return idx_1000, idx_5000, factor_base
示例#10
0
文件: 050.py 项目: TTL518/euler
def main(upbound=3943):
    primes = list(reversed(list(sieve.primerange(1, upbound))))
    for d in range(len(primes) - 1, 0, -1):
        for start in range((len(primes) - d + 1)):
            res = sum(primes[start:start + d])
            if isprime(res):
                return res
示例#11
0
 def pollardPminus1(self, N="modulus", a=7, B=2**16, pMinus1Timeout=3 * 60):
     if (N == "modulus"): N = self.modulus
     from sympy import sieve
     try:
         with timeout(seconds=pMinus1Timeout):
             brokeEarly = False
             for x in sieve.primerange(1, B):
                 tmp = 1
                 while tmp < B:
                     a = pow(a, x, N)
                     tmp *= x
             d = gcd(a - 1, N)
             if (d == N):
                 #try next a value
                 print(
                     '[x] Unlucky choice of a, try restarting Pollards P-1 with a different a'
                 )
                 brokeEarly = True
                 return
             elif (d > 1):
                 #Success!
                 self.p = d
                 self.q = N // d
                 return
             if (brokeEarly == False):
                 print(
                     "[x] Pollards P-1 did not find the factors with B=%s" %
                     B)
     except TimeoutError:
         print("[x] Pollard P-1 Timeout Exceeded")
示例#12
0
def p249(N):
    # Initialization
    total = 0
    S = list(sieve.primerange(2, N))
    curr = defaultdict(int)
    prev = defaultdict(int)

    # Dynamic programming
    for n, p in enumerate(S):
        if n == 0:
            curr[p] += 1
        else:
            curr[p] += 1
            for sum, v in prev.items():
                curr[sum] += v
                curr[sum + p] += v
        prev = curr
        curr = defaultdict(int)

    # Add up all subset sums that are prime
    for k, v in prev.items():
        if isprime(k):
            total = (total + v) % 10**16

    return total
示例#13
0
def p204(N, k):
    """Finds the number of generalised Hamming numbers of type k up to N."""

    # Initialization
    primes = sieve.primerange(2, k + 1)
    prev = set()
    curr = set([1])

    for i, p in enumerate(primes):
        # Compute all powers of p up to N
        for new in powers_up_to(p, N):
            curr.add(new)

        # Use the previous type Hamming numbers to compute the current ones
        if i > 0:
            for nums in prev:
                for new in powers_up_to(p, ceil(N/nums)+1):
                    curr.add(new*nums)
        prev = curr.copy()

    # Return the number of Hamming numbers
    # Correct the length for the incorrectness of powers_up_to function
    total = 0
    for p in prev:
        if p <= N:
            total += 1

    return total
示例#14
0
文件: 069.py 项目: TTL518/euler
def main():
    lst = list(sieve.primerange(1, 25))
    prod = lambda x: reduce(mul, x)
    index = 1
    while prod(lst[:index]) < 10**6:
        index += 1
    return prod(lst[:index - 1])
示例#15
0
def lucas_lehmer(s) -> bool:
    """
    Lucas-Lehmer primality test.

    :param s: s
    :return: true if 'no' is prime, false otherwise
    """
    # Mersenne number:
    no = mersenne_s(s)

    # square root of s:
    sr = int(math.ceil(math.sqrt(s)))

    # trial division of number to check if s has any prime factors in [2, sqrt(s)]
    # already covered by the check performed in the function mersenne_s(), but for stringency reasons:
    for div in sieve.primerange(2, sr):
        if s % div == 0:
            print(f'M_{s} = {no} has s divide by {div}. S is not a prime')
            return False

    # building recurring list u, |u| = s - 2
    u = 4
    i = s - 2
    while i:
        u = modular_reduction(u ** 2 - 2, no, s)
        # next iteration:
        i -= 1

    return bool(u == 0)
示例#16
0
def minimum_multiple(target):
    included_primes = sieve.primerange(1, target+1)

    # 素因数とtargetを超えない指数のセットを入れていく。
    prime_factorize_sets = []

    for prime in included_primes:

        # primeにべき乗してtargetを超えない指数を探しリストにしていく。
        # 最後にそれらのべき乗をかけ合わせれば求める答え。
        index = 1
        while True:
            if prime ** index > target:
                factor_set = [prime, index-1]
                break
            else:
                index += 1

        prime_factorize_sets.append(factor_set)

    # べき乗の配列に
    factors = map(lambda x: x[0] ** x[1], prime_factorize_sets)

    # 要素を全て掛け合わせる
    answer = reduce(lambda x, y: x * y, factors)

    return answer
示例#17
0
def main():
    number_list = [str(x) for x in range(1, 8)]
    res_list = [
        int(reduce(add, x)) for x in list(permutations(number_list, 7))
    ]
    cross_set = set(res_list) & set(sieve.primerange(1234567, 7654321))
    return max(cross_set)
示例#18
0
def primewalk(n=100, draw_plot=True):
    """ Compute and draw 'prime walk' plot for primes <n
        http://tinyurl.com/primewalk
    """
    ## get magic list of primes
    primes = list(sieve.primerange(1, n))
    ## initialize; set starting point and direction
    ## (horizontal, to the right)
    x = [0]
    y = [0]
    direction = "right"
    for i in range(1, len(primes)):
        pdiff = primes[i] - primes[i - 1]
        if direction == "right":
            x.append(x[i - 1] + pdiff)
            y.append(y[i - 1])
            direction = "down"
        elif direction == "down":
            x.append(x[i - 1])
            y.append(y[i - 1] - pdiff)
            direction = "left"
        elif direction == "left":
            x.append(x[i - 1] - pdiff)
            y.append(y[i - 1])
            direction = "up"
        elif direction == "up":
            x.append(x[i - 1])
            y.append(y[i - 1] + pdiff)
            direction = "right"
    if (draw_plot):
        fig, ax = plt.subplots()
        ax.plot(x, y)
        plt.show()
    return (None)
示例#19
0
def find_prime_concatenates(current_primes, targetsize, sumlimit, solutions):
    # print("find_prime_concatenates({}, {}, {}, {})".format(
    #     current_primes, targetsize, sumlimit, solutions))
    if len(current_primes) == targetsize:
        solutions.append(current_primes)
        #print("Found Solution: {}".format(current_primes))
        return True
    else:
        # 2 can never concat new prime
        left_range = 3
        if len(current_primes) > 0:
            left_range = current_primes[-1] + 1
        for p in sieve.primerange(left_range, sieve._list[-1]):
            # 5 can never concat new prime
            if p == 5:
                continue
            if p > sumlimit:
                break
            if check_new_prime(current_primes, p):
                new_current_primes = list(current_primes)
                new_current_primes.append(p)
                if find_prime_concatenates(new_current_primes, targetsize,
                                           sumlimit - p, solutions):
                    return True  # Not, this is a non-perfect optimization because it assumes there is only one solution for a given depth part

    return False
示例#20
0
def test_generate():
    from sympy.ntheory.generate import sieve
    sieve._reset()
    assert nextprime(-4) == 2
    assert nextprime(2) == 3
    assert nextprime(5) == 7
    assert nextprime(12) == 13
    assert prevprime(3) == 2
    assert prevprime(7) == 5
    assert prevprime(13) == 11
    assert prevprime(19) == 17
    assert prevprime(20) == 19

    sieve.extend_to_no(9)
    assert sieve._list[-1] == 23

    assert sieve._list[-1] < 31
    assert 31 in sieve

    assert nextprime(90) == 97
    assert nextprime(10**40) == (10**40 + 121)
    assert prevprime(97) == 89
    assert prevprime(10**40) == (10**40 - 17)
    assert list(sieve.primerange(10, 1)) == []
    assert list(primerange(10, 1)) == []
    assert list(primerange(2, 7)) == [2, 3, 5]
    assert list(primerange(2, 10)) == [2, 3, 5, 7]
    assert list(primerange(1050, 1100)) == [1051, 1061,
        1063, 1069, 1087, 1091, 1093, 1097]
    s = Sieve()
    for i in range(30, 2350, 376):
        for j in range(2, 5096, 1139):
            A = list(s.primerange(i, i + j))
            B = list(primerange(i, i + j))
            assert A == B
    s = Sieve()
    assert s[10] == 29

    assert nextprime(2, 2) == 5

    raises(ValueError, lambda: totient(0))

    raises(ValueError, lambda: reduced_totient(0))

    raises(ValueError, lambda: primorial(0))

    assert mr(1, [2]) is False

    func = lambda i: (i**2 + 1) % 51
    assert next(cycle_length(func, 4)) == (6, 2)
    assert list(cycle_length(func, 4, values=True)) == \
        [17, 35, 2, 5, 26, 14, 44, 50, 2, 5, 26, 14]
    assert next(cycle_length(func, 4, nmax=5)) == (5, None)
    assert list(cycle_length(func, 4, nmax=5, values=True)) == \
        [17, 35, 2, 5, 26]
    sieve.extend(3000)
    assert nextprime(2968) == 2969
    assert prevprime(2930) == 2927
    raises(ValueError, lambda: prevprime(1))
示例#21
0
def euler51():
    for p in sieve.primerange(100000, 999999):
        s = str(p)
        if s.count('0') == 3 and replace_count(s, '0') == 8 \
            or s.count('1') == 3 and replace_count(s, '1') == 8 \
                or s.count('2') == 3 and replace_count(s, '2') == 8:
            print(s)
            break
示例#22
0
def euler51():
    for p in sieve.primerange(100000, 999999):
        s = str(p)
        if s.count('0') == 3 and replace_count(s, '0') == 8 \
            or s.count('1') == 3 and replace_count(s, '1') == 8 \
                or s.count('2') == 3 and replace_count(s, '2') == 8:
            print(s)
            break
示例#23
0
def solve():
    window = 100 * log(LIMIT)  # From brief testing, this naive formula holds
    primes = sieve.primerange(LIMIT**0.5 - window, LIMIT**0.5 + window)

    return np.prod(
        min([(a, b) for a, b in combinations(primes, 2) if a * b < LIMIT
             and sorted(str(a * b)) == sorted(str((a - 1) * (b - 1)))],
            key=lambda x: np.prod(x) / np.prod(np.array(x) - 1)))
示例#24
0
文件: 049.py 项目: TTL518/euler
def main():
    primes = list(sieve.primerange(1488, 10000))
    for p in primes:
        a = p + 3330
        b = p + 6660
        if a in primes and b in primes and set(str(p)) == set(str(a)) == set(
                str(b)):
            return str(p) + str(a) + str(b)
示例#25
0
def is_goldbach_composite(n):
    if isprime(n):
        return True
    for prime in sieve.primerange(1, n):
        for ds in double_squares(n):
            if prime + ds == n:
                return True
    return False
示例#26
0
文件: RSATool.py 项目: Binzt/CTF
 def smallPrimes(self, n="n", upperlimit=1000000):
     if (n == "n"): n = self.modulus
     from sympy import sieve
     for i in sieve.primerange(1, upperlimit):
         if (n % i == 0):
             self.p = i
             self.q = n // i
             return
示例#27
0
def group_prime_permutations():
    prime_dict = {}

    for prime in sieve.primerange(1000, 9999):
        prime_key = key(prime)
        prime_dict.setdefault(prime_key, [])
        prime_dict[prime_key].append(prime)

    return prime_dict
示例#28
0
def euler35():
    primes = set(['2', '5'] + [
        str(p) for p in sieve.primerange(2, 1000000)
        if not search('[024568]', str(p))
    ])
    print(
        sum(
            all(q in primes for q in [p[n:] + p[:n] for n in range(1, len(p))])
            for p in primes))
示例#29
0
def solve():
    candidates = set(
        map(
            str,
            filter(lambda x: not any(int(digit) % 2 == 0 for digit in str(x)),
                   sieve.primerange(LIMIT))))

    return 1 + sum(
        all(n[i:] + n[:i] in candidates for i in range(len(n)))
        for n in candidates)
示例#30
0
def primes():
    """
    Prime Numbers: Positive integers with exactly two factors\n
    OEIS A000040
    """

    upper = 2
    while True:
        upper *= 2
        yield from sieve.primerange(upper // 2, upper)
示例#31
0
def nextgen():
    global gen,S
    #eprint(gen)
    newgen = set()
    S += len(gen)
    for n in gen:
        for p in sieve.primerange(1,min(sqrtlim,lim//n+1)):
            newgen.add(p*n)
    del gen
    gen = newgen 
示例#32
0
def euler46():
    i = 7
    found = False
    while not found:
        found = True
        i += 2
        if isprime(i) or any(
                is_square((i - p) / 2) for p in sieve.primerange(2, i)):
            found = False
    print(i)
示例#33
0
def nonRepeatingPrimes(n):
    primes = list(sieve.primerange(2, n))
    output = {}
    for prime in primes:
        digs = num2Dig(prime)
        s = set(digs)
        if 0 in s: continue
        if len(s) == len(digs):  # non repeating
            output[prime] = s
    return output
示例#34
0
def solve():
    primes = set(sieve.primerange(LIMIT))
    tests = set()
    for b in primes.copy():
        for a in range(-b, LIMIT, 2):
            tests.add((a, b))

    composites = set()
    return prod(
        max(tests, key=lambda x: consecutive_primes(*x, primes, composites)))
示例#35
0
def count_squarefree(N):
  '''Return the number of squarefree integers below N.'''

  mobius = [1] * int(sqrt(N))
  for p in sieve.primerange(2, int(sqrt(N))):
    for i in xrange(p, int(sqrt(N)), p):
      mobius[i-1] = -mobius[i-1]
    for i in xrange(p**2, int(sqrt(N)), p**2):
      mobius[i-1] = 0

  return sum([(N / p**2) * mobius[p-1] for p in xrange(1, int(sqrt(N)))])
示例#36
0
def euler50():
    limit = 100
    primes = SortedSet(sieve.primerange(1, limit))
    prime_sums = SortedSet()
    prime_sums.add(0)
    consecutive = 0
    for p in primes:
        prime_sums.add(prime_sums[-1] + p)
    for i in range(consecutive, len(prime_sums)):
        for j in range(i - consecutive - 1, -1, -1):
            if prime_sums[i] - prime_sums[j] > limit:
                break
            if isprime(prime_sums[i] - prime_sums[j]):
                consecutive = i - j
                result = prime_sums[i] - prime_sums[j]
    print(result)
示例#37
0
def euler60():
    limit = 10000
    primes = set(sieve.primerange(2, limit))
    for p0 in primes:
        s0 = set(find_concatenable_primes(p0, primes))
        for p1 in s0:
            s1 = set(find_concatenable_primes(p1, primes))
            i1 = s0 & s1
            for p2 in i1:
                s2 = set(find_concatenable_primes(p2, primes))
                i2 = i1 & s2
                for p3 in i2:
                    s3 = set(find_concatenable_primes(p3, primes))
                    i3 = i2 & s3
                    if len(i3) == 1:
                        print(p0+p1+p2+p3+sum(i3))
                        return
示例#38
0
def prime_square_remainder(target):
  '''Calculate the least value n such that the remainder exceeds the
  target.'''
  for i, p in enumerate(sieve.primerange(1, 1e6)):
    bini = bin(i+1)[2:][::-1]
    leftterm = 1
    rightterm = 1
    for j, elem in enumerate(bini):
      if elem == '1':
        leftterm *= (2**j * p + 1)
        if j != 0:
          rightterm *= (1 - 2**j * p)
        else:
          rightterm *= (p - 1)
        leftterm %= p**2
        rightterm %= p**2
    if (leftterm + rightterm) % p**2 > target:
      return i + 1
示例#39
0
def circular_primes(max_n):
    primes = list(sieve.primerange(2,max_n))
    count = 0
    prime_set = set(primes)
    for n in primes:
        isCircPrime = True
        n_queue = collections.deque(str(n))
        
        for _ in range(len(n_queue)):
            n_queue.rotate(1)
            if n_queue[0] == '0':
                continue           
            p_val = int("".join(n_queue))
            if p_val not in prime_set:
                isCircPrime = False
                break
        if isCircPrime:
             count = count +1
    return count
示例#40
0
def perfect_hashing_init(K):
    max_key = max(K)
    # from Bertrand's postulate, for each n >= 1, there is a prime p, such that n < p <= 2n
    p = random.choice(list(sieve.primerange(max_key + 1, 2 * max_key + 1)))
    m = K.length
    T = Array.indexed(0, m - 1)
    h = _get_random_universal_hash_function(p, m)
    mapped_keys = [[] for _ in range(m)]
    for k in K:
        mapped_keys[h(k)].append(k)
    secondary_sizes = [len(keys) ** 2 for keys in mapped_keys]
    for j, size in enumerate(secondary_sizes):
        if size == 1:
            T[j] = (lambda _: 0, Array([mapped_keys[j][0]], start=0))
        elif size > 1:
            h_ = None
            S = None
            while S is None:
                h_ = _get_random_universal_hash_function(p, size)
                S = _construct_secondary_hash_table_no_collisions(mapped_keys[j], size, h_)
            T[j] = (h_, S)
    return T, h
示例#41
0
def quadratic_primes(max_coefficient):
  '''Calculate the product of the coefficients that generate the most primes
  for a sequence of n starting with n=0 of the form:

  n^2 + an + b

  for |a| < max_coefficient and |b| < max_coefficient.
  '''

  b_lst = list(sieve.primerange(1, max_coefficient))

  max_n = 0
  for a in range(-max_coefficient + 1, max_coefficient):
    for b in b_lst:
      n = 0
      while isprime(n**2 + a * n + b):
        n += 1
      if n > max_n:
        max_n = n
        max_product = a * b

  return max_product
示例#42
0
def genseq():
    for i in sieve.primerange(1000, 3333):
        for j in range(1000, 3333, 2):
            if isprime(i + j) and isprime(i + j * 2):
                yield [i, i + j, i + j * 2]
示例#43
0
def euler41():
    print(max(p for p in sieve.primerange(2, 7654321) if is_pandigital(p)))
示例#44
0
文件: 27.py 项目: omgspace/Euler
from sympy import sieve

sieve.extend(2000000)

maxcount = 0
amax = 0
bmax = 0

for b in sieve.primerange(0,1000):
    for a in xrange(-2*(b/2)-1, 1000, 2):
        term = lambda n: n**2 + a*n + b
        i = 0
        count = 0
        while sieve.__contains__(term(i)):
            i += 1
            count += 1

        if count > maxcount: 
            maxcount = count
            amax = a
            bmax = b

print maxcount
print amax, bmax
示例#45
0
def euler49():
    for p in sieve.primerange(1488, 9999):
        for i in range(1, 9999-p):
            if is_permutation(p, p+i) and is_permutation(p, p+2*i) and isprime(p+i) and isprime(p+2*i):
                print(str(p)+str(p+i)+str(p+2*i))
                return
示例#46
0
from sympy.ntheory import isprime
from sympy import sieve

def is_truncprime(n):
    s = str(n)
    for i in xrange(1, len(s)):
        if not isprime(int(s[0:len(s)-i])): return False
        if not isprime(int(s[i:len(s)])): return False
    return True

limit = 1000000

print sum(n for n in sieve.primerange(10, limit) if is_truncprime(n))
示例#47
0
def PrimeList1to1000():
	return sieve.primerange(1,1001)
示例#48
0
def test_generate():
    from sympy.ntheory.generate import sieve
    sieve._reset()
    assert nextprime(-4) == 2
    assert nextprime(2) == 3
    assert nextprime(5) == 7
    assert nextprime(12) == 13
    assert prevprime(3) == 2
    assert prevprime(7) == 5
    assert prevprime(13) == 11
    assert prevprime(19) == 17
    assert prevprime(20) == 19

    sieve.extend_to_no(9)
    assert sieve._list[-1] == 23

    assert sieve._list[-1] < 31
    assert 31 in sieve

    assert nextprime(90) == 97
    assert nextprime(10**40) == (10**40 + 121)
    assert prevprime(97) == 89
    assert prevprime(10**40) == (10**40 - 17)

    assert list(sieve.primerange(10, 1)) == []
    assert list(sieve.primerange(5, 9)) == [5, 7]
    sieve._reset(prime=True)
    assert list(sieve.primerange(2, 12)) == [2, 3, 5, 7, 11]

    assert list(sieve.totientrange(5, 15)) == [4, 2, 6, 4, 6, 4, 10, 4, 12, 6]
    sieve._reset(totient=True)
    assert list(sieve.totientrange(3, 13)) == [2, 2, 4, 2, 6, 4, 6, 4, 10, 4]
    assert list(sieve.totientrange(900, 1000)) == [totient(x) for x in range(900, 1000)]
    assert list(sieve.totientrange(0, 1)) == []
    assert list(sieve.totientrange(1, 2)) == [1]

    assert list(sieve.mobiusrange(5, 15)) == [-1, 1, -1, 0, 0, 1, -1, 0, -1, 1]
    sieve._reset(mobius=True)
    assert list(sieve.mobiusrange(3, 13)) == [-1, 0, -1, 1, -1, 0, 0, 1, -1, 0]
    assert list(sieve.mobiusrange(1050, 1100)) == [mobius(x) for x in range(1050, 1100)]
    assert list(sieve.mobiusrange(0, 1)) == []
    assert list(sieve.mobiusrange(1, 2)) == [1]

    assert list(primerange(10, 1)) == []
    assert list(primerange(2, 7)) == [2, 3, 5]
    assert list(primerange(2, 10)) == [2, 3, 5, 7]
    assert list(primerange(1050, 1100)) == [1051, 1061,
        1063, 1069, 1087, 1091, 1093, 1097]
    s = Sieve()
    for i in range(30, 2350, 376):
        for j in range(2, 5096, 1139):
            A = list(s.primerange(i, i + j))
            B = list(primerange(i, i + j))
            assert A == B
    s = Sieve()
    assert s[10] == 29

    assert nextprime(2, 2) == 5

    raises(ValueError, lambda: totient(0))

    raises(ValueError, lambda: reduced_totient(0))

    raises(ValueError, lambda: primorial(0))

    assert mr(1, [2]) is False

    func = lambda i: (i**2 + 1) % 51
    assert next(cycle_length(func, 4)) == (6, 2)
    assert list(cycle_length(func, 4, values=True)) == \
        [17, 35, 2, 5, 26, 14, 44, 50, 2, 5, 26, 14]
    assert next(cycle_length(func, 4, nmax=5)) == (5, None)
    assert list(cycle_length(func, 4, nmax=5, values=True)) == \
        [17, 35, 2, 5, 26]
    sieve.extend(3000)
    assert nextprime(2968) == 2969
    assert prevprime(2930) == 2927
    raises(ValueError, lambda: prevprime(1))
示例#49
0
def euler10():
    print(sum(sieve.primerange(2, 2e6)))
示例#50
0
def CheckGConjecture(n):
	for i in sieve.primerange(1,n):
		if ((n-i)/2)**0.5 == int(((n-i)/2)**0.5):
			return True
	return False
示例#51
0
from sympy import sieve

limit = 10000

prosti = list(sieve.primerange(2, limit))
trazeni = set(p +2*(n**2) for p in prosti for n in xrange(1, limit))
odd_composite = set(2*n+1 for n in xrange(1, limit)).difference(prosti)
print min(odd_composite.difference(trazeni))
示例#52
0
def euler27():
    print(max(((prime_streak(a, b), a * b) 
               for b in sieve.primerange(2, 1000) for a in range(-b+2, 0, 2)))[1])
示例#53
0
def euler35():
    primes = set(['2', '5'] + [str(p) for p in sieve.primerange(2, 1000000) if not search('[024568]', str(p))])
    print(sum(all(q in primes for q in [p[n:] + p[:n] for n in range(1, len(p))]) for p in primes))
示例#54
0
文件: picklePrimes.py 项目: ebensh/pe
def main(maxPrime, outputPath):
  with open(outputPath, 'w') as f:
    cPickle.dump(list(sieve.primerange(2, maxPrime)), f, cPickle.HIGHEST_PROTOCOL)
示例#55
0
from sympy.ntheory import isprime
from sympy import sieve

limit = 1000000

def is_circ(n):
    s, i = str(n), 0
    if '0' in s or '2' in s or '4' in s or '6' in s or '8' in s: return False
    while i < len(s):
        if not isprime(int(s)):
                return False
        s = s[1:len(s)]+s[0]
        i+=1
    return True


print len(set(x for x in sieve.primerange(3, limit) if is_circ(x))) + 1
'''
Solution to Euler Problem Ten

@author VegasAce
last modified: 11/13/15 --happy birthday!

Solution:  142913828922 Time to run:  0.943645954132
'''

import sympy,time
from sympy import sieve

start_time = time.time()
totalSum = 0
TWO_MILL = 2000000

for element in sieve.primerange(1,TWO_MILL):
    totalSum += element

print 'Solution: ' , totalSum , ' Time to run: ' , (time.time() - start_time)