Esempio n. 1
0
def isGoldbach(n):
    if n % 2 == 0 or isPrime(n):  # Not a composite
        return True
    for i in range(1, n + 1):
        remainder = n - 2 * i**2
        if remainder <= 0:
            return False
        elif isPrime(remainder):
            return True
Esempio n. 2
0
def compute():
    timer = time.time()
    for i in range(1000, 3341):
        if isPrime(i) and isPrime(i + 3330) and isPrime(i + 6660) and set(
            [d for d in str(i)]) == set([d for d in str(i + 3330)]) and set([
                d for d in str(i)
            ]) == set([d for d in str(i + 6660)]) and i != 1487:
            ans = int(str(i) + str(i + 3330) + str(i + 6660))
            break
    print("Answer is " + str(ans) + ". Completed in " +
          str(time.time() - timer) + " seconds.")
    return ans
Esempio n. 3
0
def p3(x=600851475143):
    below = []
    for i in xrange(2, int(x**0.5)):
        if x % i == 0:
            if isPrime(x / i):
                print x / i
                return
            below.append(i)
    for i in below[::-1]:
        if isPrime(i):
            print i
            return
    return x
def p3(x=600851475143):
    below=[]
    for i in xrange(2,int(x**0.5)):
        if x%i==0:
            if isPrime(x/i):
                print x/i
                return
            below.append(i)
    for i in below[::-1]:
        if isPrime(i):
            print i
            return
    return x
Esempio n. 5
0
def compute():
    timer = time.time()
    tp = []
    i = 11
    while len(tp) < 11:
        if isPrime(i):
            s = str(i)
            if all(
                    isPrime(int(s[:j])) and isPrime(int(s[j:]))
                    for j in range(1, len(s))):
                tp.append(i)
        i += 2
    print("Answer is " + str(sum(tp)) + ". Completed in " +
          str(time.time() - timer) + " seconds.")
    return sum(tp)
Esempio n. 6
0
def genPrimes():
    yield 2
    i = 3
    while True:
        if util.isPrime(i):
            yield i
        i += 2
Esempio n. 7
0
def test1B(args={'dbg': 1}):
    '''(3, N, 2) util.isPrime() & list primes'''
    test = 'test1B'
    dbg = 1
    #    print('{} args={}'.format(test, args))
    if 'dbg' in args: dbg = args['dbg']
    if 'N' in args: N = args['N']
    if dbg == 0: print('.', end='')
    pList = []
    m = 2
    while m < N / 2:
        m *= 2
    pList.append(m)
    #    if dbg: print('m = {}'.format(m))
    for n in range(3, N, 2):
        if util.isPrime(n):
            m = n
            while m < N / n:
                m *= n
            pList.append(m)
    if dbg:
        #        print('{}'.format(pList))
        M = 1
        for p in pList:
            M *= p
        print('\n{} {:,}'.format(test, M), end=' ')
Esempio n. 8
0
def _keyGen(lamda=64, down=100, up=10000):
    '''
    lamda: 参数
    '''
    p = lamda
    prikey_len = lamda * 2 + random.randint(1, lamda)
    pubkey_len = lamda * 3 + random.randint(1, lamda)
    
    prikey = random.randrange(2**(prikey_len-1) + 1, 2**prikey_len)
    while prikey % 2 == 0:
        prikey = random.randrange(2**(prikey_len-1) + 1, 2**prikey_len)

    pubkeynum = pubkey_len + lamda
    pubkey = []
    c = 2**pubkey_len
    d = 2**lamda

    n = random.randrange(down, up)
    while util.isPrime(n) == False:
        n = random.randrange(down, up)

    pubkey = []
    for i in range(0, pubkeynum):
        q = random.randrange(0, c // prikey)
        r = random.randrange(0, d)
        pubkey.append(prikey * q + n * r)
    
    return (prikey, pubkey, n)
Esempio n. 9
0
def sumPrimesBelow(goal):
	primes = []
	for n in [i for i in range(2, goal)]:
		if isPrime(n):
			primes.append(n)

	print ("Number of primes less than %d: %d" % (goal, len(primes)))
	print ("Sum of primes less than %d: %d" % (goal, sum(primes)))
Esempio n. 10
0
def compute():
    timer = time.time()
    primes = []
    for i in range(1000000):
        s = str(i)
        l = [int(s[j:] + s[:j]) for j in range(len(s))]
        if all(isPrime(val) for val in l):
            primes = primes + l
    ans = len(set(primes))
    print("Answer is " + str(ans) + ". Completed in " +
          str(time.time() - timer) + " seconds.")
    return ans
Esempio n. 11
0
def compute():
    timer = time.time()
    i = 644
    consecutive = []
    while len(consecutive) < 4:
        if len([x for x in getFactors(i) if isPrime(x)]) == 4:
            consecutive.append(i)
        else:
            consecutive = []
        i += 1
    print("Answer is " + str(consecutive[0]) + ". Completed in " +
          str(time.time() - timer) + " seconds.")
    return consecutive[0]
Esempio n. 12
0
def p58(n=0.10):
    corners = [3, 5, 7]
    #upper right, upper left, lower left, lower right is never prime
    differences = [10, 12, 14]
    #Notice that as the grid expands one rotation, all these differences increase by 8 every time
    statistics = [3, 3, 5]
    #current side length, currrent number of primes, total number of corners
    while statistics[1] / (statistics[2] + 0.0) > n:
        corners = [corners[i] + differences[i] for i in xrange(3)]
        differences = [i + 8 for i in differences]
        update = [2, sum([int(isPrime(i)) for i in corners]), 4]
        statistics = [statistics[i] + update[i] for i in xrange(3)]
    print statistics[0]
Esempio n. 13
0
def countPrimes(n, exc):
    primes = []
    if 0 in exc:
        a = 1
    else:
        a = 0
    for x in range(a, 10):
        s = str(n)
        for val in exc:
            s = s[:val] + str(x) + s[val + 1:]
        if s[0] != '0' and isPrime(int(s)):
            primes.append(int(s))
    return primes
Esempio n. 14
0
def p41():
    #enumerate 7 digit pandigitals in decreasing order
    for i in xrange(5039,-1,-1):
        factoradic=toFactoradic(i,6)
        array=[str(i) for i in xrange(1,8)]
        permutation=''
        for j in factoradic:
            permutation+=array[int(j)]
            del array[int(j)]
        if isPrime(int(permutation)):
            print permutation
            return
    #enumerate four digit pandigitals in decreasing order
    for i in xrange(23,-1,-1):
        factoradic=toFactoradic(i,3)
        array=[str(i) for i in xrange(1,5)]
        permutation=''
        for j in factoradic:
            permutation+=array[int(j)]
            del array[int(j)]
        if isPrime(int(permutation)):
            print permutation
            return
Esempio n. 15
0
def p41():
    #enumerate 7 digit pandigitals in decreasing order
    for i in xrange(5039, -1, -1):
        factoradic = toFactoradic(i, 6)
        array = [str(i) for i in xrange(1, 8)]
        permutation = ''
        for j in factoradic:
            permutation += array[int(j)]
            del array[int(j)]
        if isPrime(int(permutation)):
            print permutation
            return
    #enumerate four digit pandigitals in decreasing order
    for i in xrange(23, -1, -1):
        factoradic = toFactoradic(i, 3)
        array = [str(i) for i in xrange(1, 5)]
        permutation = ''
        for j in factoradic:
            permutation += array[int(j)]
            del array[int(j)]
        if isPrime(int(permutation)):
            print permutation
            return
Esempio n. 16
0
def compute():
    timer = time.time()
    ans = 0
    maxprimes = 0
    for b in range(1000, 0, -1):
        if isPrime(
                b
        ):  # b must be positive and prime as when n=0, ans = b which must be prime
            for a in range(-999, 1000):
                primes = 1
                for n in range(1, b):
                    if isPrime(n**2 + a * n + b):
                        primes += 1
                    else:
                        break
                if primes > maxprimes:
                    maxprimes = primes
                    ans = a * b
            if maxprimes == b:  # Break when we find the largest value b where for all x, f(x) < b is prime
                break

    print("Answer is " + str(ans) + ". Completed in " +
          str(time.time() - timer) + " seconds.")
    return ans
Esempio n. 17
0
def compute():
    timer = time.time()
    i = 56003
    ans = 0
    while ans == 0:
        if isPrime(i):
            for j, combo in enumerate(powerset(range(len(str(i)))), 1):
                primes = countPrimes(i, combo)
                #                print(i, combo, primes)
                if len(primes) > 7:
                    ans = min(primes)
        i += 1
    print("Answer is " + str(ans) + ". Completed in " +
          str(time.time() - timer) + " seconds.")
    return ans
Esempio n. 18
0
def test1C(args={'dbg': 1}):
    '''uses util.isPrime() for odd #s >= 3'''
    test = 'test3'
    dbg = 1
#    print('{} args={}'.format(test, args))
    if 'dbg' in args: dbg = args['dbg']
    if 'N'   in args:   N = args['N']   
    if dbg == 0: print('.', end='')
    n, p = 2, 3
    while 1:
        if util.isPrime(p):
#            print('{} {}'.format(n, p))
            n += 1 
        if n == N+1: break
        p += 2
    if dbg: print('\n{} {:,}th prime = {:,}'.format(test, N, p), end=' ')
Esempio n. 19
0
def compute():
    timer = time.time()
    primes = getPrimes(1000000)
    longest = 0
    for i in range(len(primes) // 4):
        chain = 1
        total = primes[i]
        while total + primes[i + chain] < 1000000:
            total += primes[i + chain]
            chain += 1
        if chain > longest and isPrime(total):
            longest = chain
            ans = total
    print("Answer is " + str(ans) + ". Completed in " +
          str(time.time() - timer) + " seconds.")
    return ans
Esempio n. 20
0
def p27():
    max_consecutive_primes=40
    pair=(1,41) #store the a and b values
    for b in primes:
        for a in xrange(-999,1000,2):
            consecutive_primes=1
            for n in xrange(1,b):
                num=n*n+a*n+b
                if num < 0:
                    break
                if isPrime(num):
                    consecutive_primes+=1
                else:
                    break
            if consecutive_primes > max_consecutive_primes:
                pair=(a,b)
                max_consecutive_primes=consecutive_primes
    print pair, pair[0]*pair[1]
Esempio n. 21
0
def compute():
    timer = time.time()
    ans = 0
    for length in range(9, 0, -1):
        if ans == 0:
            perms = sorted(list(
                permutations([str(i) for i in range(1, length + 1)])),
                           reverse=True)
            for p in perms:
                s = ''
                for d in p:
                    s = s + d
                if isPrime(int(s)):
                    ans = int(s)
                    break
    print("Answer is " + str(ans) + ". Completed in " +
          str(time.time() - timer) + " seconds.")
    return ans
Esempio n. 22
0
def p27():
    max_consecutive_primes = 40
    pair = (1, 41)  #store the a and b values
    for b in primes:
        for a in xrange(-999, 1000, 2):
            consecutive_primes = 1
            for n in xrange(1, b):
                num = n * n + a * n + b
                if num < 0:
                    break
                if isPrime(num):
                    consecutive_primes += 1
                else:
                    break
            if consecutive_primes > max_consecutive_primes:
                pair = (a, b)
                max_consecutive_primes = consecutive_primes
    print pair, pair[0] * pair[1]
Esempio n. 23
0
def test2(args={'dbg': 1}):
    '''range(3, N) isPrime(n)'''
    test = 'test2'
    dbg = 1
    #    print('{} args={}'.format(test, args))
    if 'dbg' in args: dbg = args['dbg']
    if 'N' in args: N = args['N']
    if dbg == 0: print('.', end='')
    p, s = [2], 2
    for n in range(3, N, 2):
        if util.isPrime(n):
            p.append(n)
            s += n


#    print('{}'.format(p))
    if dbg:
        print('\n{} the sum of primes below {:,} = {:,}'.format(test, N, s),
              end=' ')
Esempio n. 24
0
def test1(args={'dbg': 1}):
    '''uses util.isPrime() (3, sqrt(N)+1, 2)'''
    test = 'test1'
    dbg = 1
    #    print('{} args={}'.format(test, args))
    if 'dbg' in args: dbg = args['dbg']
    if 'N' in args: N = args['N']
    if dbg == 0: print('.', end='')
    p = []
    M = int(math.sqrt(N))
    for i in (range(3, M + 1, 2)):
        if N % i == 0:
            if util.isPrime(i):
                p.append(i)


#    if dbg: print(p)
    if dbg:
        print('\n{} largest prime factor = {:,}'.format(test, p[-1]), end=' ')
Esempio n. 25
0
def test1(args={'dbg': 1}):
    '''(3, N, 2) util.isPrime()'''
    test = 'test1'
    dbg = 1
    #    print('{} args={}'.format(test, args))
    if 'dbg' in args: dbg = args['dbg']
    if 'N' in args: N = args['N']
    if dbg == 0: print('.', end='')
    m = 2
    while m < N / 2:
        m *= 2
    M = m
    #    if dbg: print('m = {}'.format(m))
    for n in range(3, N, 2):
        if util.isPrime(n):
            m = n
            while m < N / n:
                m *= n
            M *= m
    if dbg: print('\n{} {:,}'.format(test, M), end=' ')
Esempio n. 26
0
def compute():
    timer = time.time()
    value = 1
    increment = 2
    primes = 0
    diagonals = 1
    found = False
    while not found:
        for i in range(4):
            value += increment
            if isPrime(value):
                primes += 1
            diagonals += 1
        if primes / diagonals < 0.1:
            found = True
            ans = (diagonals + 1) / 2
        increment += 2
    print("Answer is " + str(ans) + ". Completed in " +
          str(time.time() - timer) + " seconds.")
    return ans
Esempio n. 27
0
def test2(args={'dbg': 1}):
    '''uses util.isPrime() i=odd while(i*i <= N)'''
    test = 'test2'
    dbg = 1
    #    print('{} args={}'.format(test, args))
    if 'dbg' in args: dbg = args['dbg']
    if 'N' in args: N = args['N']
    if dbg == 0: print('.', end='')
    p = []
    i = 3
    while i * i <= N:
        if N % i == 0:
            #            print('{} is a factor of N ({})'.format(i, N/i), end=' ')
            if util.isPrime(i):
                p.append(i)
        i += 2


#    if dbg: print('{} {} {} {}'.format(N, i, p, p[-1]))
    if dbg:
        print('\n{} Largest prime factor = {:,}'.format(test, p[-1]), end=' ')
Esempio n. 28
0
def test3(args={'dbg': 1}):
    '''uses util.isPrime() (i <= M) (M % i)'''
    test = 'test3'
    dbg = 1
    #    print('{} args={}'.format(test, args))
    if 'dbg' in args: dbg = args['dbg']
    if 'N' in args: N = args['N']
    if dbg == 0: print('.', end='')
    pf = []
    i = 3
    M = N
    while i <= M:
        while M % i == 0:
            if util.isPrime(i):
                #                if dbg: print('M={}, i={}'.format(M, i))
                pf.append(i)
                M = int(M / i)
        i += 1


#    if dbg: print('prime factors = {}'.format(pf))
    if dbg:
        print('\n{} largest prime factor = {:,}'.format(test, pf[-1]), end=' ')
Esempio n. 29
0
'''
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.
'''
import util

MAX_NUM = 2000000

sum_val = 1
for i in range(0, MAX_NUM):
    if util.isPrime(i):
        sum_val += i

print sum_val
Esempio n. 30
0
'''
The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143 ?
'''
import math
import util

VALUE = 600851475143

maxPrime = 0
for i in range(1, int(math.sqrt(VALUE)), 2):
    if VALUE % i == 0 and util.isPrime(i):
            maxPrime = i

print maxPrime
Esempio n. 31
0
'''
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

What is the 10,001st prime number?
'''
import util

MAX_NUM = 10001

current_number = 1
prime_count = 1

while prime_count < MAX_NUM:
    current_number += 1

    if util.isPrime(current_number):
        prime_count += 1

print current_number