class TestSieve(unittest.TestCase):
    def setUp(self):
        self.primes = Primes(100)

    def test_size(self):
        self.assertEqual(self.primes.size, 100)

    def test_isPrime_83(self):
        self.assertEqual(self.primes.is_prime[83], True)

    def test_first_5_primes(self):
        self.assertEqual(self.primes.first(5), [2, 3, 5, 7, 11])

    def test_primes_up_to_13(self):
        self.assertEqual(self.primes.up_to(13), [2, 3, 5, 7, 11, 13])

    def test_primes_up_to_100(self):
        self.assertEqual(self.primes.up_to(100), [
            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
        ])

    def test_primes_1000th_prime_is_7919(self):
        s = Primes(10000)
        self.assertEqual(s.first(1000)[-1], 7919)
Example #2
0
def Euler_123(low = 10**10):
	''' Returns the nth prime that has a remainder above low when using
			the given formula
	'''
	p = Primes(10**6)
	primes = p.pList()
	for x in range(0,len(primes)):
		n = mpz(x+1)
		p = mpz(primes[x]-1)**n + mpz(primes[x]+1)**n
		if p % mpz(primes[x])**2 > low:
			return n
Example #3
0
def pe41():
    """
    >>> pe41()
    7652413
    """
    primes = Primes(1000000)
    for perm in permutations(range(7, 0, -1)):
        n = list_num(perm)
        if primes.is_prime(n):
            return n
    return -1
Example #4
0
 def test_primes(self):
     primes = Primes()
     assert 0 not in primes
     assert 1 not in primes
     taketen = primes[1:11]
     correct = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
     taketen = list(taketen)
     assert taketen == correct
     for x in range(1, 11):
         assert primes[x] == correct[x - 1]
     assert 104744 not in primes
     assert primes[10001] == 104743
     itr = iter(primes)
     for _ in range(10100):
         next(itr)
     assert list(primes.countdown(29))[::-1] == correct
Example #5
0
File: 035.py Project: Ballaw/MyBin
def Euler_35(top=10**6):
	''' Returns the number of circular primes below the top
	'''
	def rotate(num):
		return int(str(num)[-1] + str(num)[0:-1])
	count = 0
	primes = Primes(top)
	primes.sieve()
	for val in primes.pList():
		val2 = rotate(val)
		while val2 != val:
			if not primes.isPrime(val2):
				break
			val2 = rotate(val2)
		if val == val2:
			count += 1
	return count
Example #6
0
def pe27():
    """
    >>> pe27()
    (-59231, (-61, 971, 71))
    """
    m = (0, 0, 0)
    primes = Primes(15000)
    for a in range(-999, 1000):
        for b in range(max(2, 1 - a), 1000):
            n, cnt = 0, 0
            while 1:
                p = n * (n + a) + b
                if primes.is_prime(p):
                    cnt += 1
                else:
                    break
                n += 1
            if cnt > m[2]:
                m = (a, b, cnt)
    return (m[0] * m[1], m)
Example #7
0
def pe27():
    """
    >>> pe27()
    (-59231, (-61, 971, 71))
    """
    m = (0, 0, 0)
    primes = Primes(15000)
    for a in range(-999, 1000):
        for b in range(max(2, 1 - a), 1000):
            n, cnt = 0, 0
            while 1:
                p = n * (n + a) + b
                if primes.is_prime(p):
                    cnt += 1
                else:
                    break
                n += 1
            if cnt > m[2]:
                m = (a, b, cnt)
    return (m[0] * m[1], m)
def generate_code(n, k):
    primes = Primes(n + k)
    primes_list = primes.primes_list
    #primes_list=primes.primes_3mod4()
    print(primes_list)

    words = gen_words(primes_list[0:k])
    primes = primes_list[k:n + k]
    print(primes_list)
    print(primes)
    code = [[legendre_symbol(w, p) for p in primes] for w in words]
    return code
Example #9
0
 def test_factors(self):
     primes = Primes()
     assert primes.factors(0) == []
     assert primes.factors(1) == []
     assert primes.factors(2) == [2]
     assert primes.factors(6) == [2, 3]
     assert primes.factors(8) == [2, 2, 2]
     assert primes.factors(29) == [29]
def generate_jacobi_code(n, k):
    nlog = int(math.log(n, 2))
    primes = Primes(nlog + k + 1)
    primes_list = primes.primes_list
    #primes_list=primes.primes_3mod4()
    print(primes_list)

    words = gen_words(primes_list[0:k])
    primes = primes_list[k:nlog + k]
    encoders = gen_words(primes)
    print(primes_list)
    print(encoders)
    code = [[jacoby_symbol(w, m) for m in encoders] for w in words]
    return code
Example #11
0
File: 131.py Project: Ballaw/MyBin
def Euler_131(top=6*10**3):
	''' Returns the number of primes below the input
		where n**3+p*n**2 is a perfect cube
	'''
	from primes import isPrime
	from primes import Primes
	foo = lambda p,n: n**3 + p * n**2
	def bsearch(l, val, low, high):
		while low <= high:
			mid = (low + high) // 2
			if val < l[mid]:
				high = mid - 1
				continue
			elif val > l[mid]:
				low = mid + 1
				continue
			elif val == l[mid]:
				return True
		return False

	cubelist = [x**3 for x in range(1,top)]
	cubetop = top
	a = Primes(top)
	count = 0
	for p in a.pList(top):
		for n in range(1,top):
			tmp = foo(p,n)
			while tmp > cubelist[-1]:
				cubelist.append(cubetop**3)
				cubetop += 1
			if bsearch(cubelist, tmp, 0, cubetop-1):
				print(p,n,tmp)
				count += 1
				break
	return count

	'''
Example #12
0
class TestSieve(unittest.TestCase):
    def setUp(self):
        self.primes = Primes(100)

    def test_size(self):
        self.assertEqual(self.primes.size, 100)

    def test_isPrime_83(self):
        self.assertEqual(self.primes.is_prime[83], True)

    def test_first_5_primes(self):
        self.assertEqual(self.primes.first(5), [2, 3, 5, 7, 11])

    def test_primes_up_to_13(self):
        self.assertEqual(self.primes.up_to(13), [2, 3, 5, 7, 11, 13])

    def test_primes_up_to_100(self):
        self.assertEqual(self.primes.up_to(100),
                         [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])

    def test_primes_1000th_prime_is_7919(self):
        s = Primes(10000)
        self.assertEqual(s.first(1000)[-1], 7919)
Example #13
0
def pe49(limit=10000):
    """
    >>> pe49()
    (2969, 6299, 9629)
    """
    pr = Primes()
    for num in range(1111, limit):
        sn = str(num)
        if sn.find('0') >= 0: continue
        if pr.is_prime(num):
            pp = {num : 1}
            for p in permutations(list(sn)):
                n = int(''.join(p))
                if pr.is_prime(n):
                    pp[n] = 1
            primes = sorted(pp.keys())
            pl = len(primes)
            for a in range(pl):
                if primes[a] == 1487: continue
                for b in range(a+1, pl):
                    c = (primes[a] + primes[b]) >> 1
                    if c in pp:
                        return (primes[a], c, primes[b])
    return None
Example #14
0
 def test_trunc_primes(self):
     primes = Primes()
     assert primes.truncatable(3797)
     primes = Primes()
     trunc = []
     for prime in primes:
         if primes.truncatable(prime):
             trunc.append(prime)
         if len(trunc) == 10:
             assert sum(trunc) == 8920
             break
Example #15
0
def main():
    a= Primes(2, 100000, 2000)
    p = random.choice(a)
    q = random.choice(a)
    #print("随机生成两个素数p和q. p=",p," q=",q)
    n = p * q
    s = (p-1)*(q-1)
    #print("The p is ", p)
    #print("The q is ", q)
    #print("The n(p*q) is ",n)
    e = co_prime(s)
    #e = 5
    #print("根据e和(p-1)*(q-1))互质得到: e=", e)
    d = find_d(e,s)
    #print("根据(e*d) 模 ((p-1)*(q-1)) 等于 1 得到 d=", d)
    #print("公钥:   n=",n,"  e=",e)
    #print("私钥:   n=",n,"  d=",d)
    pbvk = (n,e,d)
    return pbvk
Example #16
0
 def test_is_circular(self):
     primes = Primes()
     assert primes.is_circular(2)
     assert primes.is_circular(971)
     assert not primes.is_circular(999953)
Example #17
0
def primes():
    return Primes()
Example #18
0
import sys
sys.path.append('C:\\Users\\bob\\comp-sci\\project-euler\\toolkit')
from primes import Primes

p = Primes(1000000)
is_prime = p.is_prime
p_list = p.primes_list

def solve():
    most_terms, prime = 0, 0
    for terms in range(1, 547):
        for i in range(len(p_list) - terms):
            p_sum = sum(p_list[i:i+terms])
            if p_sum > 1000000:
                break
            if is_prime(p_sum):
                most_terms, prime = terms, p_sum
                break
    return prime

Example #19
0
File: 77.py Project: mdonahoe/euler
"""
project euler #77
matt donahoe



i enjoyed thinking of this one. did some back of the envelope (literally)

discovered a dynamic programming solution
"""

from primes import Primes
p=Primes(5000)

ways = {} #ways.get((n,p),0) = number of ways to sum to n using only primes >= p
primes = []
n=1
while s<=50000000:
	n+=1
	s = 0
	if p.is_prime(n):
		s = 1
		primes.append(n)
	for x in primes[::-1]:
		s+=ways.get((n-x,x),0)
		ways[(n,x)] = s
	print n,s
Example #20
0
def empty_Primes():
    from primes import Primes
    new_primes = Primes()
    return new_primes
Example #21
0
def test_prime_100th_element():
    """Test method first returns correct element."""
    from primes import Primes
    Primes = Primes()
    assert Primes.first(100)[99] == 541
Example #22
0
def test_primes_slice():
    """Test method first returns correct slice."""
    from primes import Primes
    Primes = Primes()
    assert Primes.first(20)[-5:] == [53, 59, 61, 67, 71]
Example #23
0
 def test_primes_1000th_prime_is_7919(self):
     s = Primes(10000)
     self.assertEqual(s.first(1000)[-1], 7919)
Example #24
0
 def button_handle_random(self, event):  # 按钮(随机素数)事件
     a = Primes(2, 5000, 1000)
     p = random.choice(a)
     q = random.choice(a)
     self.content_P.set("%s" % p)
     self.content_Q.set("%s" % q)
Example #25
0
#!/usr/bin/python3
'''
Primes generator using Sieve of Eratosthenes
Use -l to limit output or use Ctrl+C to interrupt.
'''

import argparse
import sys
from primes import Primes

argument_parser = argparse.ArgumentParser('Primes generator')
argument_parser.add_argument('-l', dest='limit', type=int, default=None)
limit = argument_parser.parse_args().limit

prime_numbers = Primes()
for prime in prime_numbers:
    if limit and prime > limit:
        sys.exit()
    print(prime)
Example #26
0
def ListOfPrimes(num):
    listofPrimenumbers = []
    for i in range(2, num):
        if Primes(i):
            listofPrimenumbers.append(i)
    return listofPrimenumbers
Example #27
0
 def test_primes_1000th_prime_is_7919(self):
     s = Primes(10000)
     self.assertEqual(s.first(1000)[-1], 7919)
Example #28
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
What is the smallest odd composite
that cannot be written as the sum of a prime and twice a square?
"""

from primes import Primes

_SQ = [i * i << 1 for i in range(100)]
primes = Primes()


def is_goldbach(n):
    res = False
    for i in range(100):
        t = n - _SQ[i]
        if t < 2:
            break
        if primes.is_prime(t):
            res = True
            break
    return res


def pe46():
    """
    >>> pe46()
    5777
    """
    limit = 10000
Example #29
0
 def setUp(self):
     self.primes = Primes(100)
Example #30
0
def test_prime_80thth_element():
    """Test method first returns correct element."""
    from primes import Primes
    Primes = Primes()
    assert Primes.first(80)[79] == 409
Example #31
0
 def setUp(self):
     self.primes = Primes(100)
Example #32
0
 def test_totient(self):
     correct = [(2, 1), (3, 2), (4, 2), (5, 4), (6, 2), (7, 6), (8, 4),
                (9, 6), (10, 4), (4079147, 4074720)]
     primes = Primes()
     for (k, v) in correct:
         assert primes.totient(k) == v
Example #33
0
from primes import Primes
testP = [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]


print Primes.first(168) == testP
print Primes.first(1000)[-1] == 7919
Example #34
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Solve project euler 58

Investigate the number of primes
that lie on the diagonals of the spiral grid.
"""

from primes import Primes

primes = Primes(30000)


def pe58(p=0.1):
    """
    >>> pe58()
    26241
    """
    l = 7
    ps = 8
    d = 49
    ds = 13
    while ps > p * ds:
        l += 2
        i = l - 1
        ps += primes.is_prime(d + i) + primes.is_prime(
            d + 2 * i) + primes.is_prime(d + 3 * i)
        d += i << 2
        ds += 4
    return l
Example #35
0
import timeit
from triangular import count_factors
from triangular import gen_triangular_number
from primes import Primes

i = 1

while True:
    i +=1
    pobj = Primes(i)
    t = gen_triangular_number(i)
    factors = count_factors(pobj, t)
    if factors >= 500:
        print ("factors", factors, "t", t)
        break
"""
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
"""

from primes import Primes

primes = Primes(10000)
print(list(primes.prime_factors((600851475143))))
Example #37
0
 def test_consecutive_sum_max(self):
     primes = Primes()
     assert (2 == primes.consecutive_sum_max(5))
     assert (0 == primes.consecutive_sum_max(11))
     assert (6 == primes.consecutive_sum_max(41))
Example #38
0
from primes import Primes

n = i = 1
p = Primes()
percent = 1

diagonals = 1 # this takes into account the center (1)
prime_diagonals = 0

while percent > 0.1:
    for x in range(4):
        n+=2*i  
        prime_diagonals += p.is_prime(n)
    diagonals += 4    
    i+=1
    percent = float(prime_diagonals) / diagonals
    print prime_diagonals, '/', diagonals, ',', percent

print 'side =', int(n**(0.5)), 'primes =', prime_diagonals, '/', diagonals, percent
Example #39
0
 def test_consecutive_sum_max_length(self):
     primes = Primes()
     assert primes.consecutive_sum_max_length(50) == (41, 6)
Example #40
0
'''
import maths
primesd = maths.primesd(10**6)
primes = [x for x in primesd.keys() if primesd.get(x) is 1]
'''
from primes import Primes
primes = Primes(10**6)
ps = primes.pList()


def Euler_50():
    high = 0
    for i in range(10):
        sums = 0
        x = 0
        if i % 10000 == 0:
            print('new', i)
        for j in ps[i:]:
            x += 1
            sums += j
            if sums > 10**6: break
            if primes.isPrime(sums):
                if x > high:
                    high = x
                    maxs = sums
                #;print('high:',high,'sum:',sums,'i:',primes.pList(i))
    return maxs


if __name__ == '__main__':
    print(Euler_50())
Example #41
0
'''
import maths
primesd = maths.primesd(10**6)
primes = [x for x in primesd.keys() if primesd.get(x) is 1]
'''
from primes import Primes
primes = Primes(10**6)
ps = primes.pList()
def Euler_50():
    high = 0
    for i in range(10):
        sums = 0
        x = 0
        if i%10000==0:
            print('new',i)
        for j in ps[i:]:
            x+=1
            sums +=j
            if sums>10**6:break
            if primes.isPrime(sums):
                if x>high:high = x;maxs=sums
                #;print('high:',high,'sum:',sums,'i:',primes.pList(i))
    return maxs


if __name__=='__main__':
    print(Euler_50())
Example #42
0
        # Prints the time needed to covers the onion shell
        ts2 = time.time()
        print (a, ts2-ts)
        ts = ts2


N = 1000        # N is half the side
L = 2*N-1       # L is the side of the square

# Creates a matrix, initialized to 0
# Each elements will represent the number of primes generated
matrix = [[0]*L for i in range(L)]


# Primes generator
primes = Primes()

# For the moment the maximum sequence has 0 length
# Each time we find a longer sequence we will record it here
# together with its parameters (point in the square, ...)
maxi = {'n': 0}

for a, b in get_coeffs(N):
    i = a + N - 1       # indices in the matrix
    j = b + N - 1   

    f = make_fun(a, b)

    # how many primes does f produces?
    n = 0
    while True:
Example #43
0
        # Prints the time needed to covers the onion shell
        ts2 = time.time()
        print(a, ts2 - ts)
        ts = ts2


N = 1000  # N is half the side
L = 2 * N - 1  # L is the side of the square

# Creates a matrix, initialized to 0
# Each elements will represent the number of primes generated
matrix = [[0] * L for i in range(L)]

# Primes generator
primes = Primes()

# For the moment the maximum sequence has 0 length
# Each time we find a longer sequence we will record it here
# together with its parameters (point in the square, ...)
maxi = {'n': 0}

for a, b in get_coeffs(N):
    i = a + N - 1  # indices in the matrix
    j = b + N - 1

    f = make_fun(a, b)

    # how many primes does f produces?
    n = 0
    while True: