示例#1
0
    41 = 2 + 3 + 5 + 7 + 11 + 13

This is the longest sum of consecutive primes that adds to a prime below one-hundred.

The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.

Which prime, below one-million, can be written as the sum of the most consecutive primes?
"""

from modules.matlib import isPrime, nextPrime

mxl = 0  # maximum length of consecutive primes list
mxsm = 0  # sum of longest consecutive primes list

s = 2  # start
while s < 1000000:  # while start is below 1 milion
    cp = []  # consecutive primes
    t = s  # start of second loop
    while (t + sum(cp) < 1000000) and isPrime(
        t + sum(cp)
    ):  # while sum of consecutive primes plus the last one is below 100
        cp.append(t)  # append prime to consecutive primes list
        if len(cp) > mxl:  # if list of consecutive primes is longest and sum of those consecutive primes is prime
            mxl = len(cp)  # lenght of current list
            mxsm = sum(cp)  # sum of consecutive primes
        t = nextPrime(t)  # continue with next prime
    s = nextPrime(s)  # continue with next prime

print(mxsm)  # output sum of longest consecutive primes list
示例#2
0
#!/usr/bin/python3

"""
Problem 7 - 10001st prime

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?
"""

from modules.matlib import nextPrime

n = 2 # first prime
for i in range(10000):
    n = nextPrime(n) # find next prime 10000 times

print(n) # output result
示例#3
0
Problem 37 - Truncatable primes

The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.

Find the sum of the only eleven primes that are both truncatable from left to right and right to left.

NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.
"""

from modules.matlib import isPrime
from modules.matlib import nextPrime

def isTruncatablePrime(n):
    n = str(n)
    if len(n) < 2: return False
    for i in range(1, len(n), 1):
        if not isPrime(int(n[i:])) or not isPrime(int(n[:-i])): return False
    return True

sm = 0 # sum of truncatable primes
c = 0 # count of truncatable primes
p = 11 # truncatable prime candidate

while c < 11:
    if isTruncatablePrime(p):
        c += 1
        sm += p
    p = nextPrime(p)

print(sm)