def isTruncPrime(num):
    num = str(num)
    if len(num) < 2: # 2,3,5,7 are not considered to be truncatable primes
        return False
    for i in range(0,len(num)): # Truncate left to right
        if (not eulerlib.isPrime(int(num[i:]))):
            return False
    for i in range(1,len(num)): # Truncate right to left
        if (not eulerlib.isPrime(int(num[:i]))):
            return False
    return True
Example #2
0
def solve():
    sieve(1000)
    qty = 2  # 2 and 5
    for p in xrange(3, 1000000, 2):
        pstr = str(p)
        if (
            all(c in "1379" for c in pstr)
            and isPrime(p, presieve=False)
            and all(isPrime(int(pstr[i:] + pstr[:i]), presieve=False) for i in range(1, len(pstr)))
        ):
            qty += 1
    return qty
Example #3
0
def solve():
    maxPrimes = 40
    maxCoefProd = 41
    for b in dropwhile(lambda p: p<=41, primeIter(bound=1000)):
        for a in xrange(-999, 1000):
            if a == b+1 or a == b-1:
                # The quadratic can be factored into (n ± b)(n ± 1) and so will
                # produce no more than 2 consecutive primes.
                continue
            if a*a >= 4*b:
                bound = b
                d = sqrt(a*a - 4*b)
                x1 = (-a+d)/2
                x2 = (-a-d)/2
                if 0 < x1 < bound:
                    bound = x1
                if 0 < x2 < bound:
                    bound = x2
                if bound <= maxPrimes:
                    continue
            n = 1
            while isPrime(n*n + a*n + b):
               n += 1
            if n > maxPrimes:
                maxPrimes = n
                maxCoefProd = a*b
    return maxCoefProd
Example #4
0
def solve():
    sieve(500)
    P = [Fraction(2 if isPrime(i) else 1, 3) for i in xrange(1, 501)]
    N = [1 - p for p in P]
    state = [Fraction(1, 500)] * 500
    for primal in [P if c == 'P' else N for c in 'PPPPNNPPPNPPNPN']:
        state = jump(map(operator.mul, state, primal))
    return sum(state)
Example #5
0
def solve():
    accum = 0
    for n1 in primeIter(bound=100000000):
        n = n1 - 1
        for d in xrange(2, int(n**0.5)+1):
            if n % d == 0 and not isPrime(d + n // d):
                break
        else:
            accum += n
    return accum
def solve():
    import itertools
    from eulerlib import isPrime

    # This could be a bit faster, but most of the time is spent in checking if num is a prime or not

    circular = 1 # 2 is prime
    for num in range(3,1000000,2):
        if (isPrime(num)):
            circular += 1 # Assume the prime is circular
            # Make sure every rotation is a prime too
            num = str(num)
            numL = [num[x] for x in range(0,len(num))] # Number represented as a list of digits
            for i in range(0,len(numL)):
                numL.append(numL.pop(0)) # List Rotation
                rot = int("".join(numL)) # Back into a num you go
                if (not isPrime(rot)):
                    circular -= 1 # Nope, we were wrong, this prime isn't circular :(
                    break
    return circular
Example #7
0
def solve():
    sieve(10**7)
    new = [(d,d) for d in range(1, 10)]
    accum = 0
    for _ in xrange(12):
        newer = []
        for n,s in new:
            for d in xrange(10):
                n2 = n*10 + d
                s2 = s + d
                q,r = divmod(n2, s2)
                if r == 0:
                    newer.append((n2, s2))
                    if isPrime(q, presieve=False):
                        for e in [1,3,7,9]:
                            m = n2 * 10 + e
                            if isPrime(m, presieve=False):
                                accum += m
        new = newer
    return accum
def solve():
    import math
    from eulerlib import isPrime

    pList = [2]
    pSums = [2]
    LIMIT = 1000000

    # Get some primes and sum them consecutively
    i = 1 # Keep track of the index of pSums
    num = 3 # Keep track of the prime number
    add = 0 
    while (add + num < LIMIT):
        if isPrime(num):
            pList.append(num)
            add = pSums[i-1] + num
            pSums.append(add)
            i += 1
        num += 2

    # Find the max consecutive sum starting from each prime
    maxAdds = 0; maxNum = 0
    endLen = len(pSums)
    pSums.reverse() # Flip the list
    for prime in pList:
        for add in pSums[:endLen]:
            # Summing from the current prime consecutively,
            # this add is the max prime you can get
            if isPrime(add):
                maxNum = add
                maxAdds = len(pList[pList.index(prime):])-pSums.index(add)
                endLen = pSums.index(add) # New prime starts must be able to beat the current maxAdds
                break
            pSums[pSums.index(add)] -= prime # Subtract prime from each sum to get the sums starting from the next prime
        # Break if maxAdds is at it's highest possible
        if maxAdds > len(pList[pList.index(prime):]):
            break

    return maxAdds
def solve():
    import itertools
    from eulerlib import isPrime

    # Bruteforce approach:
    # 1. Choose a 1st term, check if it's prime, else test next term
    # 2. Get the permutations of the 1st term
    # 3. Choose an arithmetic add
    # 4. Check if 2nd and 3rd terms are prime, else test next add
    # 5. Check if their permutations, print solution
    for i in range(1001,3333,2):
        if not isPrime(i): continue
        # Get the permutations of the 1st number in the arirthmetic sequence
        perms = itertools.permutations(str(i), 4)
        perms = list(perms)
        for k in range(len(perms)):
            perms[k] = ''.join(perms[k])
        for j in range(2,3333,2):
            if not isPrime(i+j) or not isPrime(i+2*j): continue
            if ((str(i+j) in perms) and (str(i+2*j) in perms)):
                if i != 1487:
                    return(str(i)+str(i+j)+str(i+2*j))
def euler41():
    largest = 0
    for n in range(3,11):
        print("Generating permutations for n = ", n, end="")
        perms = generateStringPermutations(
            "".join([str(i) for i in range(1, n)]))
        print("...done.")
        print("Checking primes...")
        for p in perms:
            num = int(p)
            if isPrime(num):
                #print(num)
                largest = max(largest, num)
        print("done.")
    print("Largest prime found =", largest)
Example #11
0
def primeSets(digits):
    if len(digits) == 0:
        return 1
    else:
        accum = 0
        d = min(digits)
        igits = digits - {d}
        for ds in subsets(igits):
            if len(ds) == 8:
                continue
            arrangements = sum(isPrime(int(''.join(p)))
                               for p in permutations(ds+(d,)))
            if arrangements != 0:
                accum += arrangements * primeSets(igits.difference(ds))
        return accum
Example #12
0
def solve():
    for p in allprimes():
        pstr = str(p)
        for d in '012':
            indices = [i for i,c in enumerate(pstr) if c == d]
            if indices:
                for subdex in subsets(indices, nonempty=True):
                    qty = 1
                    for d2 in range(int(d)+1, 10):
                        s2 = pstr
                        for i in subdex:
                            s2 = s2[:i] + str(d2) + s2[i+1:]
                        if isPrime(int(s2)):
                            qty += 1
                            if qty == 8:
                                return p
def solve():
    import eulerlib
    import itertools

    # Create a base pandigital and examine all permutations to see if any of them are prime and large
    # Can optimize by searching backwards instead (from basePan = 987654321)
    basePan = ""
    panDigMax = 0
    for n in range(1,10):
        basePan += str(n) # Concat the n digit string to the base to create a pandigital
        perms = list(itertools.permutations(basePan)) # All permutations of a pandigital are pandigital
        for perm in perms:
            panDig = int("".join(perm)) # Form an int from the iterable
            if (eulerlib.isPrime(panDig) and panDig > panDigMax):
                panDigMax = panDig

    return panDigMax
def solve():
    import eulerlib

    # Maximization of consecutive primes from the quadratic: n^2 + an + b
    # Where |a| < 1000 and |b| < 1000 and n starts at 0
    maxab = 0
    maxprimes = 0
    bPrimes = eulerlib.PrimeSieve(1000)
    for a in range(-999,1000,2): # a must be odd to satisify n = 1 case (1+a+b=prime)
        for b in bPrimes: # b must be pos prime to satisfiy n = 0 case (0+0+b=prime)
            n = 0
            while eulerlib.isPrime(n**2 + a*n + b):
                n += 1
            if (n > maxprimes):
                maxprimes = n
                maxab = a*b

    return maxab
Example #15
0
def solve():
    maxPrime = 0
    maxTerms = 0
    primes = list(primeIter(bound=10**6))
    for i,p in enumerate(primes):
        try:
            accum = sum(primes[i+j] for j in xrange(maxTerms))
        except IndexError:
            break
        if accum >= 1000000:
            break
        for j in xrange(maxTerms, len(primes)-i):
            accum += primes[i+j]
            if accum >= 1000000:
                break
            if isPrime(accum):
                maxPrime = accum
                maxTerms = j+1
    return maxPrime
def euler46():
    """Solve problem 46 from Project Euler."""
    primes = [2,]
    n = 3
    while (True):
        if isPrime(n):
            primes.append(n)
        else:
            isGoldbach = False
            # Try to decompose the number according to formula
            # n = prime + 2x²
            # n - prime = 2x²
            # (n - prime)/2 = x²
            # sqrt((n - prime)/2) = x
            for prime in primes:
                x = math.sqrt((n - prime)/2)
                if x == math.floor(x):
                    # if x is an integer number, n is a valid composite
                    isGoldbach = True
                    break
            if not isGoldbach:
                print("Fails Goldbach =", n)
                break
        n += 2
def isStrongRightTruncHarshadPrime(n):
    return isPrime(n) and isRightTruncHarshadNumber(n//10)
def isStrongHarshadNumber(n):
    return isPrime(n / sumDigits(n)) and isHarshadNumber(n)
def isPrime(num):
    if num <= primes[-1]:
        return num in primeset # O(1)
    else:
        return eulerlib.isPrime(num) # slower (actually this shouldn't be used given the limit...)
def isPrime(num):
    if num < LIMIT:
        return isPrimeTable[num]
    else:
        return eulerlib.isPrime(num)
Example #21
0
def answers():
    for n in count(3):
        if n % 2 and n % 5 and (n - 1) % A(n) == 0 and not isPrime(n):
            yield n
# 9 = 7 + 2×1^2
# 15 = 7 + 2×2^2
# 21 = 3 + 2×3^2
# 25 = 7 + 2×3^2
# 27 = 19 + 2×2^2
# 33 = 31 + 2×1^2
# It turns out that the conjecture was false.
# What is the smallest odd composite that cannot be written as the sum of a prime and twice a square?
################################################################################

import eulerlib
import math

# Can prove the conjecture by assuming it to be true for each number until it's proven false
# n = p + 2*s means that sqrt(s) = sqrt((n-p)/2) must be an integer
primes = [2,3,5,7]; n = 9
conjecture = True
while (conjecture):
    n += 2
    if (not eulerlib.isPrime(n)):
        conjecture = False # Assume the conjecture is false
        # Find the prime p and square s that satisfies the conjecture
        for p in primes: 
            if (math.sqrt((n - p)/2) % 1 == 0):
                conjecture = True
                break
    else:
        primes.append(n)

print(n)