Esempio n. 1
0
def is_tr_prime(n):
#   One-digit numbers and non-prime numbers are
#   not truncatable primes.
    if n < 11 or not is_prime(n):
        return False

    tmp = n // 10

#   Remove one digit at a time from the right and check
#   if the resulting number is prime. Return 0 if it isn't.
    while tmp > 0:
        if not is_prime(tmp):
            return False
        tmp = tmp // 10

#   Starting from the last digit, check if it's prime, then
#   add back one digit at a time on the left and check if it
#   is prime. Return 0 when it isn't.
    i = 10
    tmp = n % i

    while tmp != n:
        if not is_prime(tmp):
            return False
        i = i * 10
        tmp = n % i

#   If it gets here, the number is truncatable prime.
    return True
Esempio n. 2
0
def main():
    start = default_timer()

    max_ = 0

    #   Brute force approach, optimized by checking only values of b where b is prime.
    for a in range(-999, 1000):
        for b in range(2, 1001):
            #           For n=0, n^2+an+b=b, so b must be prime.
            if is_prime(b):
                n = 0
                count = 0

                while True:
                    p = n * n + a * n + b

                    if p > 1 and is_prime(p):
                        count = count + 1
                        n = n + 1
                    else:
                        break

                if count > max_:
                    max_ = count
                    save_a = a
                    save_b = b

    end = default_timer()

    print('Project Euler, Problem 27')
    print('Answer: {}'.format(save_a * save_b))

    print('Elapsed time: {:.9f} seconds'.format(end - start))
Esempio n. 3
0
def tiles(L=2000):
    n, c = 1, 1
    while c <= L:
        r = 6 * n
        if is_prime(r-1):
            if is_prime(r+1) and is_prime(2*r+5): c += 1
            if is_prime(r+5) and is_prime(2*r-7): c += 1
        n += 1
    return n-1
Esempio n. 4
0
def tiles(L=2000):
    n, c = 1, 1
    while c <= L:
        r = 6 * n
        if is_prime(r - 1):
            if is_prime(r + 1) and is_prime(2 * r + 5): c += 1
            if is_prime(r + 5) and is_prime(2 * r - 7): c += 1
        n += 1
    return n - 1
Esempio n. 5
0
def main():
    start = default_timer()

    N = 1000000

    i = 1
    res = 1

    #   Using Euler's formula, phi(n)=n*prod(1-1/p), where p are the distinct
    #   primes that divide n. So n/phi(n)=1/prod(1-1/p). To find the maximum
    #   value of this function, the denominator must be minimized. This happens
    #   when n has the most distinct small prime factor, i.e. to find the solution
    #   we need to multiply the smallest consecutive primes until the result is
    #   larger than 1000000.
    while res < N:
        i = i + 1

        if is_prime(i):
            res = res * i


#   We need the previous value, because we want i<1000000
    res = res // i

    end = default_timer()

    print('Project Euler, Problem 69')
    print('Answer: {}'.format(res))

    print('Elapsed time: {:.9f} seconds'.format(end - start))
Esempio n. 6
0
def num_consec_primes(qab, isPrime):
    l, n = 0, 0
    while is_prime(qab(n), hashDic=isPrime):
        l += 1
        n += 1

    return l
Esempio n. 7
0
def num_consec_primes(qab, isPrime):
    l, n = 0, 0
    while is_prime(qab(n), hashDic=isPrime):
        l += 1
        n += 1

    return l
Esempio n. 8
0
def main():
    start = default_timer()

    #   Starting with 1, the next four numbers in the diagonal are 3 (1+2), 5 (1+2+2), 7 (1+2+2+2)
    #   and 9 (1+2+2+2+2). Check which are prime, increment the counter every time a new prime is
    #   found, and divide by the number of elements of the diagonal, which are increase by 4 at
    #   every cycle. The next four number added to the diagonal are 13 (9+4), 17 (9+4+4), 21 and 25.
    #   Then 25+6 etc., at every cycle the step is increased by 2. Continue until the ratio goes below 0.1.
    i = 1
    l = 1
    step = 2
    count = 0
    diag = 5

    while True:
        i = i + step

        if is_prime(i):
            count = count + 1

        i = i + step

        if is_prime(i):
            count = count + 1

        i = i + step

        if is_prime(i):
            count = count + 1

        i = i + step
        ratio = count / diag

        step = step + 2
        diag = diag + 4
        l = l + 2

        if ratio < 0.1:
            break

    end = default_timer()

    print('Project Euler, Problem 58')
    print('Answer: {}'.format(l))

    print('Elapsed time: {:.9f} seconds'.format(end - start))
Esempio n. 9
0
def euler10(num):
    """Finds the sum of all primes below num."""
    total = 0
    curr_number = 2
    while curr_number < num:
        if projecteuler.is_prime(curr_number):
            total += curr_number
        curr_number += 1
    return total
Esempio n. 10
0
def euler7(n):
    """Finds the n-th prime number."""
    curr_prime_index = 0
    curr_number = 2
    while True:
        if projecteuler.is_prime(curr_number):
            curr_prime_index += 1
        if curr_prime_index >= n:
            return curr_number
        curr_number += 1
Esempio n. 11
0
def max_prime_factor(num):
#   Use function defined in projecteuler.py to check if a number is prime.
    if is_prime(num):
        return num

#   If num is even, find the largest prime factor of num/2.
    if num % 2 == 0:
        return max_prime_factor(num // 2)

    else:
        i = 3

#       If num is divisible by i and i is prime, find largest
#       prime factor of num/i.
        while True:
            if num % i == 0:
                if is_prime(i):
                    return max_prime_factor(num//i)
            i = i + 2

#   Should never get here
    return -1
Esempio n. 12
0
def eight_primes(sp, i):
    """ Replace every set of i characters from sp and check if it is prime """
    l = len(sp)
    for iSet in choose(l, i):
        notPrimes = 0
        for r in replacements(sp, iSet):
            if (len(str(r)) != len(sp)) or (not is_prime(r, PRIME_DIC)):
                notPrimes += 1
            if notPrimes == 3:
                break
        if notPrimes < 3:
            return True, iSet

    return False, None
Esempio n. 13
0
def eight_primes(sp, i):
    """ Replace every set of i characters from sp and check if it is prime """
    l = len(sp)
    for iSet in choose(l, i):
        notPrimes = 0
        for r in replacements(sp, iSet):
            if (len(str(r)) != len(sp)) or (not is_prime(r, PRIME_DIC)):
                notPrimes += 1
            if notPrimes == 3:
                break
        if notPrimes < 3:
            return True, iSet

    return False, None
Esempio n. 14
0
def main():
    start = default_timer()

    count = 1
    n = 1

#   Brute force approach: start with count=1 and check every odd number
#   (2 is the only even prime), if it's prime increment count, until the
#   target prime is reached.
    while count != 10001:
        n = n + 2
#       Use the function in projecteuler.py to check if a number is prime.
        if is_prime(n):
            count = count + 1

    end = default_timer()

    print('Project Euler, Problem 7')
    print('Answer: {}'.format(n))

    print('Elapsed time: {:.9f} seconds'.format(end - start))
Esempio n. 15
0
def main():
    start = default_timer()

    #   8- and 9-digit pandigital numbers can't be prime, because
    #   1+2+...+8=36, which is divisible by 3, and 36+9=45 which is
    #   also divisible by 3, and therefore the whole number is divisible
    #   by 3. So we can start from the largest 7-digit pandigital number,
    #   until we find a prime.
    i = 7654321

    while (i > 0):
        if is_pandigital(i, len(str(i))) and is_prime(i):
            break


#       Skipping the even numbers.
        i = i - 2

    end = default_timer()

    print('Project Euler, Problem 41')
    print('Answer: {}'.format(i))

    print('Elapsed time: {:.9f} seconds'.format(end - start))
Esempio n. 16
0
def main():
    start = default_timer()

    global primes

    primes = [0] * 100

#   Generate a list of the first 100 primes.
    i = 0
    j = 0

    while j < 100:
        if is_prime(i):
            primes[j] = i
            j = j + 1
        i = i + 1

    i = 2

#   Use a function to count the number of prime partitions for
#   each number >= 2 until the one that can be written in over
#   5000 ways is found.
    while True:
        n = count(0, 0, 0, i)

        if n > 5000:
            break

        i = i + 1

    end = default_timer()

    print('Project Euler, Problem 77')
    print('Answer: {}'.format(i))

    print('Elapsed time: {:.9f} seconds'.format(end - start))
Esempio n. 17
0
def right_trunc(p, primes):
    s = str(p)
    return all(is_prime(int(s[:i]), primes, onePrime=False) for i in range(1, len(s)))
Esempio n. 18
0

def is_trunc(p, primes):
    return left_trunc(p, primes) and right_trunc(p, primes)


def left_trunc(p, primes):
    s = str(p)
    return all(is_prime(int(s[i:]), primes, onePrime=False) for i in range(1, len(s)))


def right_trunc(p, primes):
    s = str(p)
    return all(is_prime(int(s[:i]), primes, onePrime=False) for i in range(1, len(s)))


if __name__ == '__main__':

    primes = {}
    p = 2
    truncPrimes = set()

    while len(truncPrimes) < 11:
        if p > 7 and is_prime(p, primes, onePrime=False) and is_trunc(p, primes):
            print 'Adding p = {}'.format(p)
            truncPrimes.add(p)
        p += 1

    print 'Truncatable primes: {}'.format(truncPrimes)
    print 'Sum: {}'.format(sum(truncPrimes))
Esempio n. 19
0
#Project Euler Problem 130
#http://blog.dreamshire.com/project-euler-130-solution/

from projecteuler import is_prime

dnp = set()  # set of deceptive non-primes
L = 25
n = 91  # start with first valid n given in the problem description

while len(dnp) < L:
    if not is_prime(n) and pow(10, n - 1, 9 * n) == 1:
        dnp.add(n)
    n += 2

print "Project Euler 130 Solution =", sum(dnp)
Esempio n. 20
0
    We shall say that an n-digit number is pandigital if it makes use of all
    the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital
    and is also prime.

    What is the largest n-digit pandigital prime that exists?

Notes:
    Upper bound is 987654321. Let's just brute force it with itertools

    Update -- upper bound is actually 7654321!
        8 numbers will be divisible by 3, and hence so will 9. Awesome

"""

from itertools import permutations

from projecteuler import is_prime


if __name__ == '__main__':

    pMax = 1

    for i in range(2, 8):
        for p in permutations(range(1, i + 1)):
            p = int(''.join([str(el) for el in p]))
            if is_prime(p):
                pMax = max(p, pMax)

    print "pMax = {}".format(pMax)
Esempio n. 21
0
from projecteuler import is_prime
 
nmax = 55992
s = 0
inc=3
for n in range(3, nmax , 4):
  if is_prime(n): s += inc
  if is_prime(n+2): s += (inc-1)
  if n>nmax//16: inc=2
  if n>nmax//4: inc=1

print "Answer to PE135 =", s
Esempio n. 22
0
#Project Euler Problem 128
#http://blog.dreamshire.com/project-euler-128-solution/

from projecteuler import is_prime


def tiles(L=2000):
    n, c = 1, 1
    while c <= L:
        r = 6 * n
        if is_prime(r - 1):
            if is_prime(r + 1) and is_prime(2 * r + 5): c += 1
            if is_prime(r + 5) and is_prime(2 * r - 7): c += 1
        n += 1
    return n - 1


n = tiles()
print 3 * n * (n - 1) + 2 if is_prime(6 * n + 1) else 3 * n * (n + 1) + 1
Esempio n. 23
0
#http://blog.dreamshire.com/project-euler-249-solution/
#Project Euler Problem 249

from projecteuler import prime_sieve, is_prime

primes = prime_sieve(5000)
t = [1] + [0] * sum(primes)

sp = 0
for p in primes:
    sp += p
    for j in range(sp, p-1, -1):
        t[j] = (t[j] + t[j-p])

print "Project Euler 249 Solution =", (sum(t[p] for p in range(sp) if is_prime(p)) % 10**16)
Esempio n. 24
0
#Project Euler Problem 128
#http://blog.dreamshire.com/project-euler-128-solution/

from projecteuler import is_prime

def tiles(L=2000):
    n, c = 1, 1
    while c <= L:
        r = 6 * n
        if is_prime(r-1):
            if is_prime(r+1) and is_prime(2*r+5): c += 1
            if is_prime(r+5) and is_prime(2*r-7): c += 1
        n += 1
    return n-1

n = tiles()
print 3*n*(n - 1) + 2 if is_prime(6*n+1) else 3*n*(n + 1) + 1
Esempio n. 25
0
#http://blog.dreamshire.com/project-euler-249-solution/
#Project Euler Problem 249

from projecteuler import prime_sieve, is_prime

primes = prime_sieve(5000)
t = [1] + [0] * sum(primes)

sp = 0
for p in primes:
    sp += p
    for j in range(sp, p - 1, -1):
        t[j] = (t[j] + t[j - p])

print "Project Euler 249 Solution =", (sum(t[p]
                                           for p in range(sp) if is_prime(p)) %
                                       10**16)
Esempio n. 26
0
        x = [s for s in combinations(range(l), i)]
        CHOOSE[l, i] = x
        return x


def replacements(sp, iSet):
    for a in range(10):
        yield int(''.join([str(a) if i in iSet else el
                           for (i, el) in enumerate(sp)]))


if __name__ == '__main__':

    for p in primes():
        if p % 1000 < 3:
            print p
        sp = str(p)
        l = len(sp)
        areEightPrimes = False
        for i in range(1, l):
            (areEightPrimes, iSet) = eight_primes(sp, i)
            if areEightPrimes:
                print 'p    = {}'.format(p)
                print 'iSet = {}'.format(iSet)
                for r in replacements(sp, iSet):
                    print '\tr = {}'.format(r)
                    print '\tis_prime(r) = {}'.format(is_prime(r))
                break
        if areEightPrimes:
            break
Esempio n. 27
0
        x = [s for s in combinations(range(l), i)]
        CHOOSE[l, i] = x
        return x


def replacements(sp, iSet):
    for a in range(10):
        yield int(''.join(
            [str(a) if i in iSet else el for (i, el) in enumerate(sp)]))


if __name__ == '__main__':

    for p in primes():
        if p % 1000 < 3:
            print p
        sp = str(p)
        l = len(sp)
        areEightPrimes = False
        for i in range(1, l):
            (areEightPrimes, iSet) = eight_primes(sp, i)
            if areEightPrimes:
                print 'p    = {}'.format(p)
                print 'iSet = {}'.format(iSet)
                for r in replacements(sp, iSet):
                    print '\tr = {}'.format(r)
                    print '\tis_prime(r) = {}'.format(is_prime(r))
                break
        if areEightPrimes:
            break
Esempio n. 28
0
#Project Euler Problem 130
#http://blog.dreamshire.com/project-euler-130-solution/

from projecteuler import is_prime

dnp = set()    # set of deceptive non-primes
L = 25
n = 91    # start with first valid n given in the problem description

while len(dnp) < L:
    if not is_prime(n) and pow(10, n-1, 9*n) == 1:
        dnp.add(n)
    n += 2

print "Project Euler 130 Solution =", sum(dnp)
Esempio n. 29
0
"""

from math import sqrt
from projecteuler import is_prime


def goldbach_was_right(o, p):
    """ See if the differnce between o and p is twice a square """
    x = sqrt((o - p) / 2.)
    return x == int(x)


if __name__ == '__main__':

    primes = {1, 2}

    o = 3
    while True:
        if is_prime(o):
            primes.add(o)
        else:
            if any([goldbach_was_right(o, p) for p in primes]):
                pass
            else:
                break
        # Only odds
        o += 2

    print o
Esempio n. 30
0
        ret = ''
        for i in range(0, len(counter_str)):
            while len(seqq) != 0 and seqq[len(seqq) - 1] == i:
                ret += d_str
                seqq.pop()
            ret += counter_str[i]
        while len(seqq):
            ret += d_str
            seqq.pop()
        yield int(ret)

S = 0
n = 10

for d in range(0, 10):
    prime_found = False
    N = 0
    for M in range(n, 0, -1):
        for counter in range(0, 10 ** (n - M)):
            counter_str = str(counter)
            counter_str = ((n - M) - len(counter_str)) * '0' + counter_str

            for candidate in intermediate_combine(M, d, counter_str):
                 if len(str(candidate)) == n and is_prime(candidate):
                     prime_found = True
                     S += candidate
                     N += 1
        if prime_found:
            break
print(S)
Esempio n. 31
0
def main():
    start = default_timer()

    N = 10000

    primes = sieve(N)

    found = 0
    p1 = 3

    #   Straightforward brute force approach
    while p1 < N and not found:
        #       If p1 is not prime, go to the next number.
        if primes[p1] == 0:
            p1 = p1 + 2
            continue

        p2 = p1 + 2

        while p2 < N and not found:
            #           If p2 is not prime, or at least one of the possible concatenations of
            #           p1 and p2 is not prime, go to the next number.
            if primes[p2] == 0 or not is_prime(
                    int(str(p1) + str(p2))) or not is_prime(
                        int(str(p2) + str(p1))):
                p2 = p2 + 2
                continue

            p3 = p2 + 2

            while p3 < N and not found:
                #               If p3 is not prime, or at least one of the possible concatenations of
                #               p1, p2 and p3 is not prime, got to the next number.
                if primes[p3] == 0 or not is_prime(int(str(p1)+str(p3))) or not is_prime(int(str(p3)+str(p1))) or\
                        not is_prime(int(str(p2)+str(p3))) or not is_prime(int(str(p3)+str(p2))):
                    p3 = p3 + 2
                    continue

                p4 = p3 + 2

                while p4 < N and not found:
                    #                   If p4 is not prime, or at least one of the possible concatenations of
                    #                   p1, p2, p3 and p4 is not prime, go to the next number.
                    if primes[p4] == 0 or not is_prime(int(str(p1)+str(p4))) or not is_prime(int(str(p4)+str(p1))) or\
                            not is_prime(int(str(p2)+str(p4))) or not is_prime(int(str(p4)+str(p2))) or\
                            not is_prime(int(str(p3)+str(p4))) or not is_prime(int(str(p4)+str(p3))):
                        p4 = p4 + 2
                        continue

                    p5 = p4 + 2

                    while p5 < N and not found:
                        #                       If p5 is not prime, or at least one of the possible concatenations of
                        #                       p1, p2, p3, p4 and p5 is not prime, go to the next number
                        if primes[p5] == 0 or not is_prime(int(str(p1)+str(p5))) or not is_prime(int(str(p5)+str(p1))) or\
                                not is_prime(int(str(p2)+str(p5))) or not is_prime(int(str(p5)+str(p2))) or\
                                not is_prime(int(str(p3)+str(p5))) or not is_prime(int(str(p5)+str(p3))) or\
                                not is_prime(int(str(p4)+str(p5))) or not is_prime(int(str(p5)+str(p4))):
                            p5 = p5 + 2
                            continue


#                       If it gets here, the five values have been found.
                        n = p1 + p2 + p3 + p4 + p5
                        found = 1

                    p4 = p4 + 2

                p3 = p3 + 2

            p2 = p2 + 2

        p1 = p1 + 2

    end = default_timer()

    print('Project Euler, Problem 60')
    print('Answer: {}'.format(n))

    print('Elapsed time: {:.9f} seconds'.format(end - start))