コード例 #1
0
def isConcatPrimePair(p1, p2):
    pair = getPair(p1, p2)
    if pair[0] in primePairsSet:
        if pair[1] in primePairsSet:
            return True
    else:
        if euler.isPrime(pair[0]) and euler.isPrime(pair[1]):
            primePairsSet.update(pair)
            return True
        else:
            return False
コード例 #2
0
def check(a, b, c, d, e):
    nums = map(str, [a, b, c, d, e])
    for perm in perms:
        new = nums[perm[0]] + nums[perm[1]]
        if not (isPrime(int(new))):
            return False
    return True
コード例 #3
0
ファイル: project_euler_58.py プロジェクト: johnlspouge/Euler
def isTestedPrime( n ):
    if n <= MAX_PRIME:
        return n in PRIME_SET
    elif n <= MAX_TEST:
        return isPrime( n, PRIMES )
    else:
        raise Exception( 'n is too large to test.' )
コード例 #4
0
def primeWithRepeat_is(numberOfDigits_i, digit_i):
    digitOther_is = list(DIGIT_S)
    digitOther_is.remove(digit_i)
    repeat_is = [digit_i for i in range(0, numberOfDigits_i)]
    for nonRepeats_i in range(0, numberOfDigits_i):
        if nonRepeats_i == 0 and numberOfDigits_i % 2 == 0:
            continue
        candidate_is = []
        for c in combinations(range(0, numberOfDigits_i), nonRepeats_i):
            if c[0] != 0 and digit_i == 0:
                continue
            for c1 in product(digitOther_is, repeat=nonRepeats_i):
                if c[0] == 0 and c1[0] == 0:
                    continue
                c0 = list(deepcopy(repeat_is))
                assert (len(c0) == numberOfDigits_i)
                assert (len(c) == nonRepeats_i)
                for j in range(0, len(list(c))):
                    c0[c[j]] = c1[j]
                primeMaybe = int(''.join(map(str, c0)))
                candidate_is.append(primeMaybe)
                #print( c, i, c0, j, primeMaybe)
        primeWithRepeat_is = []
        for candidate_i in candidate_is:
            if numberOfDigits_i < DIGIT_BIG and candidate_i in primea:
                primeWithRepeat_is.append(candidate_i)
            elif DIGIT_BIG <= numberOfDigits_i and isPrime(
                    candidate_i, primes):
                primeWithRepeat_is.append(candidate_i)
        if len(primeWithRepeat_is) != 0:
            break
    return digit_i, numberOfDigits_i - nonRepeats_i, len(
        primeWithRepeat_is), sum(primeWithRepeat_is)
コード例 #5
0
ファイル: 37.py プロジェクト: ArturoBlazquez/Project-Euler
def truncatableLeft(a):
    num = str(a)
    while len(num) > 1:
        num = num[1:]
        if not isPrime(int(num)):
            return False
    return True
コード例 #6
0
def smallestPrimeOfEightMemberFamily(numString):
    DIGITS = "***"

    # Generate digit pattern and all permutations.
    pattern = ''.join([
        ''.join(['x' for x in range(len(numString[0:-1:]) - len(DIGITS))]),
        DIGITS
    ])
    patterns = list(map(lambda x: ''.join(x), set(permutations(pattern))))

    # Check the digit patterns to determine if a number is an eight-member family.
    for pat in patterns:
        patMarker = [i for i, x in enumerate(pat) if x == '*']
        candidatePattern = ''.join(
            ['*' if i in patMarker else x for i, x in enumerate(numString)])
        tally = 0
        smallestInFamily = 0
        for i in range(10):
            # If no prime has been found by now (0, 1, 2), then it won't be an eight-member family.
            if i == 3 and tally == 0:
                break

            number = candidatePattern.replace('*', str(i))
            if number[0] == '0':
                continue

            if euler.isPrime(int(number)):
                tally += 1
                if tally == 1:
                    smallest = int(candidatePattern.replace('*', str(i)))

                if tally == 8:
                    return smallest

    return 0
コード例 #7
0
ファイル: project_euler_60.py プロジェクト: johnlspouge/Euler
def isPrimeString( s ):
    if s in PRIMECA:
        return True
    n = int( s )
    if PRIMES[ -1 ] * PRIMES[ -1 ] < n:
        raise Exception( 'isPrimeString: PRIMES[ -1 ] * PRIMES[ -1 ] < n' )
    else:
        return isPrime( n, PRIMES )
コード例 #8
0
ファイル: project_euler_95.py プロジェクト: johnlspouge/Euler
def sumFactors(n):
    if isPrime(n, primes):
        return 1
    ps = primeFactors(n, primes)
    pPowers = primePowerFactorization(ps)
    sum = 1
    for p in pPowers.keys():
        sum *= (p**(pPowers[p] + 1) - 1) // (p - 1)
    return sum - n
コード例 #9
0
def evaluatePair(a,b):
    """determine how many consecutive primes are generated"""
    n = 0
    while True:
        fx = n**2 + a*n + b
        if isPrime(fx):
            n += 1
        else:
            break
    return n-1
コード例 #10
0
ファイル: e118.py プロジェクト: drsam94/PELC
def count_sets(permut, prev):
    global count
    if not permut:
        prod = product(prev)
        if prod not in uniq_prods:
            uniq_prods.add(prod)
            count += 1

    for end in range(len(permut)):
        candidate = get_num(permut, end)
        if isPrime(candidate):
            count_sets(permut[end+1:], prev + [candidate])
コード例 #11
0
ファイル: testEuler.py プロジェクト: jstrassburg/euler
 def testSuccess(self):
     self.assertTrue(euler.isPrime(2))
     self.assertTrue(euler.isPrime(3))
     self.assertTrue(euler.isPrime(5))
     self.assertTrue(euler.isPrime(7))
     self.assertTrue(euler.isPrime(17))
     self.assertTrue(euler.isPrime(617))
コード例 #12
0
ファイル: eu7.py プロジェクト: sefi-roee/ProjectEuler
def eu7():
    LIMIT = 10001

    candidate = 1
    numOfPrimes = 1

    while (numOfPrimes != LIMIT):
        candidate += 2
        
        if isPrime(candidate):
            numOfPrimes += 1        

    return candidate
コード例 #13
0
ファイル: p046.py プロジェクト: jbcrail/project-euler
def run():
    isPrime = {}
    for i in itertools.count(3, 2):
        isPrime[i] = euler.isPrime(i)
        if isPrime[i]:
            continue
        conjecture = False
        for j in range(i-2, 1, -2):
            if not isPrime[j]:
                continue
            n = (i-j)//2
            if isPerfectSquare(n):
                conjecture = True
                break
        if not conjecture:
            return i
コード例 #14
0
ファイル: 3.py プロジェクト: thomasgordon/project_eulers
import math
import euler
i = 1

target = 600851475143
max = math.sqrt(600851475143)
value = 0

while i < max:
    if target % i == 0 and euler.isPrime(i):
        if i > value:
            value = i
    i += 1
print(value)
コード例 #15
0
ファイル: 27.py プロジェクト: ditesh/project-euler
import math
import euler

highestPrimeCount = 0

for a in range(-999, 1000):

	for b in range(-999, 1000):

		n = -1
		primeCount = 0

		while True:

			n += 1
			prime = int(math.pow(n, 2) + a*n + b)

			if not euler.isPrime(prime):
				break

			primeCount += 1

		if primeCount > highestPrimeCount:
			highestPrimeCount = primeCount
			highestA = a
			highestB = b
		

print highestA, highestB, highestPrimeCount
コード例 #16
0
ファイル: p041.py プロジェクト: jbcrail/project-euler
def run():
    for ndigit in ["1234567"[:i] for i in range(1, 8)][::-1]:
        for num in list(map("".join, itertools.permutations(ndigit)))[::-1]:
            if euler.isPrime(int(num)):
                return int(num)
    return 0
コード例 #17
0
#!/usr/bin/python

from euler import appendDigits, appendToPrimes, isPrime

PRIMES = []
LOWER = 10**3
UPPER = 10**4
appendToPrimes(UPPER, PRIMES)

fourDigitPrimes = [p for p in PRIMES if LOWER <= p < UPPER]
assert(fourDigitPrimes[0] == 1009)
assert(isPrime(1009, PRIMES))
assert(fourDigitPrimes[-1] == 9973)
assert(isPrime(9973, PRIMES))

for p1 in fourDigitPrimes:
    digits1 = []
    appendDigits(p1, digits1)
    for p0 in fourDigitPrimes:
        if p1 <= p0:
            break
        assert(p0 < p1)
        digits0 = []
        appendDigits(p0, digits0)
        if digits0 != digits1:
            continue
        else:
            p2 = p1 + (p1 - p0) # next in the arithmetic series
            assert(p1 < p2)
            if p2 not in fourDigitPrimes:
                continue
コード例 #18
0
ファイル: e111.py プロジェクト: drsam94/PELC
from euler import isPrime
from itertools import permutations
N = 10
ans = 0
for d in range(0, 10):
    for M in range(N-1, 1, -1):
        curr = set() # make sure we don't repeat answers
        for extra in range(0, 10**(N-M)):
            for locs in permutations(range(0, N), N-M):
                # build string defaulting to digit d, and filling in
                # with permutations of other digits
                num = [str(d)] * N
                for loc,digit in zip(locs,str(extra)):
                    num[loc] = digit
                num = int("".join(num))
                if num < 10**(N-1):
                    continue
                if num in curr:
                    continue
                elif isPrime(num):
                    curr.add(num)
        if len(curr) > 0:
            ans += sum(curr)
            break
print(ans)     
コード例 #19
0
from itertools import permutations
from euler import isPrime

for i in range(1000, 9999):
    if not (isPrime(i)):
        continue
    perm = permutations(str(i), 4)
    perms = []
    for p in perm:
        num = int("".join(p))
        if isPrime(num) and num not in perms:
            perms.append(num)
    for j in perms:
        if j <= i:
            continue
        for k in perms:
            if k <= j:
                continue
            if (i + k) / 2 == j:
                print i, j, k
コード例 #20
0
ファイル: 41.py プロジェクト: ditesh/project-euler
import euler

maxi = 0

for i in range(4, 10):

	perms = euler.getPerms(''.join(map(str, range(1,i))))
	newperms = []

	for perm in perms:
		newperms.append(int(perm))

	perms = newperms
	perms.sort()

	for perm in reversed(perms):

		if euler.isPrime(perm):
			print perm
			break
			
print maxi
コード例 #21
0
ファイル: test_euler.py プロジェクト: hyde1004/euler
	def test_isPrime(self):
		self.assertEqual(euler.isPrime(2), True)
		self.assertEqual(euler.isPrime(3), True)
		self.assertEqual(euler.isPrime(4), False)
		self.assertEqual(euler.isPrime(5), True)
		self.assertEqual(euler.isPrime(6), False)
コード例 #22
0
ファイル: 49.py プロジェクト: ArturoBlazquez/Project-Euler
from euler import primes, isPrime
from itertools import permutations

def get_permutations(num):
    aux=str(num)
    for i in permutations(aux):
        yield ''.join(i)
    

primes=[x for x in primes(10000) if x>=1000]

for p in primes:
    current=[]
    for permut in get_permutations(p):
        perm=int(permut)
        if isPrime(perm) and perm not in current:
            current.append(perm)
            if len(current)==3:
                current=sorted(current)
                if current[1]-current[0]==current[2]-current[1]:
                    print str(current[0])+str(current[1])+str(current[2])

#296962999629
コード例 #23
0
ファイル: e387.py プロジェクト: drsam94/PELC
def isStrongHarshad(x):
    dsum = digisum(x)
    return x%dsum == 0 and isPrime(x//dsum)
コード例 #24
0
ファイル: e387.py プロジェクト: drsam94/PELC
from euler import isPrime, digisum
def isHarshad(x):
    return x%digisum(x) == 0

def isStrongHarshad(x):
    dsum = digisum(x)
    return x%dsum == 0 and isPrime(x//dsum)

def isRTHarshad(x):
    return x < 10 or (isHarshad(x) and isRTHarshad(x//10))

N = 14
RTHarshads = [[] for n in range(0,N)]
RTHarshads[1] = [i for i in range(1,10)]

ans = 0
for n in range(2,N):
    for h in RTHarshads[n-1]:
        for k in range(0,10):
            x = h*10+k
            if isHarshad(x):
                RTHarshads[n].append(x)
    for h in RTHarshads[n]:
        if isStrongHarshad(h):
            for k in range(1,10,2):
                x = h*10+k
                if isPrime(x):
                    ans += x
print(ans)
コード例 #25
0
# Project Euler
# Problem 58

# Spiral primes

import sys
sys.path.append('../')
from euler import isPrime

n = 1
fracPrime = 1
numPrime = 0

while fracPrime >= 0.1:
    n += 2
    numOnDiags = 2 * n + 1

    num = n**2 - 3 * n + 3
    for _ in range(3):
        numPrime += 1 if isPrime(num) else 0
        num += (n - 1)

    fracPrime = numPrime / numOnDiags

print(n)
コード例 #26
0
ファイル: project_euler_41.py プロジェクト: johnlspouge/Euler
#!/usr/bin/python

from itertools import permutations
from euler import appendToPrimes
from euler import isPrime

BASE = 10
D = 4  # 2143 is a pandigital prime

PRIMES = []
appendToPrimes(10**5, PRIMES)

maximum = 0
for n in range(D, BASE):
    for p in list(permutations(range(1, n + 1))):
        i = int(''.join(map(str, p)))
        if isPrime(i, PRIMES):
            if maximum < i:
                maximum = i

print(maximum)
コード例 #27
0
from euler import range_infinite, isPrime

total = 1
primes = 0
for n in range_infinite(3, 2):
    total += 4
    if isPrime((n - 2) * (n - 2) + n - 1):
        primes += 1
    if isPrime((n - 1) * (n - 1) + 1):
        primes += 1
    if isPrime((n - 1) * (n - 1) + n):
        primes += 1

    if (primes + 0.0) / total < 0.1:
        print n
        break

#26241
コード例 #28
0
ファイル: problem3.py プロジェクト: aeronqu/projecteuler
from euler import isPrime
from math import sqrt

number = 600851475143
i = int(sqrt(number))

while i >= 2:
    if number % i == 0:
        if isPrime(i) == True:
            print i
            break
        else:
            i = i-1
    else:
        i = i -1


コード例 #29
0
ファイル: e329.py プロジェクト: drsam94/PELC
def isP(x):
    return isPrime(x)
コード例 #30
0
ファイル: e131.py プロジェクト: drsam94/PELC
from euler import isPrime

# Upper bound is hackery, probably can be made formal
N = 2000000000
cubes = [x**3 for x in range(1, 2 + int(N**(1/3)))]
# Crucial observation: For n^3 + n^2 p to be a perfect cube,
# n^2 (thus n) and n + p must be perfect cubes
ps = set()
for i,x in enumerate(cubes):
    for j in range(i+1, len(cubes)):
        if isPrime(cubes[j] - x):
            if cubes[j] - x < 1e6:
                ps.add(cubes[j] - x)
print(ps)
print(len(ps))
コード例 #31
0
ファイル: 41.py プロジェクト: ArturoBlazquez/Project-Euler
from euler import isPrime
from itertools import permutations

nums = []


def getPermutations(perm):
    for i in permutations(perm):
        yield ''.join(i)


for i in range(1, 10):
    nums.append(str(i))
    for perm in getPermutations(nums):
        if isPrime(int(perm)):
            max = perm

print max

#7652413
コード例 #32
0
ファイル: testEuler.py プロジェクト: jstrassburg/euler
 def testFailure(self):
     self.assertFalse(euler.isPrime(0))
     self.assertFalse(euler.isPrime(1))
     self.assertFalse(euler.isPrime(4))
     self.assertFalse(euler.isPrime(9))
     self.assertFalse(euler.isPrime(15))
コード例 #33
0
import math
from euler import isPrime

# What is the 10,001st prime number?
primesFound = 1
x = 3
while True:
    if isPrime(x):
        primesFound += 1
    if primesFound == 10001:
        print(x)
        break
    x += 2
コード例 #34
0
ファイル: 49.py プロジェクト: ditesh/project-euler
import euler
import sys

primeset = set()

for i in range(1001, 10000, 1):

        if euler.isPrime(i) is True: primeset = primeset | {str(i)}

diffdict = {}
primedict= {}

# Get list of permuted numbers that are primes
for prime in primeset:

        tperms=[]
        xperms=euler.getPerms(prime)

        for perm in xperms:
                if perm in primeset: tperms.append(perm)

	tperms.sort()
	tperms = tperms[tperms.index(prime):]
	primedict[prime]=tperms

	for i in range(len(tperms)-1, 0, -1):

		sub = int(tperms[i]) - int(tperms[0])

		if sub in diffdict: diffdict[sub].append({tperms[0], tperms[i]})
		else: diffdict[sub] = [{tperms[0], tperms[i]}]
コード例 #35
0
ファイル: 51.py プロジェクト: ArturoBlazquez/Project-Euler
def numPrimes(lista):
    return len([x for x in lista if isPrime(x)])
コード例 #36
0
from euler import isPrime

def highestExp(x,n):
    result = x
    count = 0
    while result <= n:
        count += 1
        result *= x
    return count

output = 1
for i in range(2,20):
    if isPrime(i):
        exponent= highestExp(i,20)
        output *= i**exponent

print output



コード例 #37
0
ファイル: 35.py プロジェクト: ditesh/project-euler
count = 1
validprimeset = set([2])
invalidset = set()

for i in range(3, 10000, 2):

	if i not in validprimeset and i not in invalidset:

		notprime = False
		perms = euler.getPerms(str(i))
		perms = set(map(int, perms))

		tmp = []
		for perm in perms:

			for j in range(2, int((math.sqrt(perm)))): tmp.append(j*perm)

			if not euler.isPrime(perm):
				invalidset = invalidset | set([perm])
				notprime = True
				break

#		invalidset = invalidset | set(tmp)

		if notprime is False:
			count += len(perms)
			validprimeset = validprimeset | perms
	

print count, len(validprimeset), len(invalidset)
コード例 #38
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?

import itertools
from euler import isPrime

largest_prime = 0
for size in range(1,10):
    # generate all the pandigital numbers of 'size'
    for i in itertools.permutations([str(x) for x in range(1,size+1)]):
        k = int("".join(i)) # convert tuple to int
        if isPrime(k) and k > largest_prime:
            largest_prime = k
            print(k)
print(largest_prime)
コード例 #39
0
ファイル: 50.py プロジェクト: ArturoBlazquez/Project-Euler
from euler import primes,isPrime

primes=primes(10**6)
realmax=0
for c in range(2,1000):
    max=0
    for i in range(0,len(primes)):
        tot=sum(primes[i:i+c])
        if tot>10**6:
            break
        elif isPrime(tot):
            if max<tot:
                max=tot

    if max>0:
        realmax=max

print realmax

#997651
コード例 #40
0
    increment = 2

    while True:
        yield num, increment
        cycle += 1
        num += increment

        if cycle == 4:
            cycle = 0
            increment += 2


primeCount = 0
sideLength = 0
for i, values in enumerate(incrementSpiralDiagonals()):
    num = values[0]
    inc = values[1]

    if euler.isPrime(num):
        primeCount += 1

    if primeCount > 0 and primeCount / (i + 1) < TARGET_PERCENTAGE:
        sideLength = inc - 1
        break

print(
    "The side length of a square spiral with a prime ratio on the diagonals where first less than {0}% is {1}."
    .format(TARGET_PERCENTAGE * 100, sideLength))

print("Program execution took {0} seconds.".format(time.clock() - startTime))
コード例 #41
0
ファイル: project_euler_46.py プロジェクト: johnlspouge/Euler
#!/usr/bin/python

from euler import isPrime, appendToPrimes

PRIMES = []
UPPER = 10**5
appendToPrimes(UPPER, PRIMES)

twoSquares = [2 * n * n for n in range(0, UPPER)]

n = 3
while True:
    while isPrime(n, PRIMES):
        n += 2
    bad = True
    for j in twoSquares:
        if n <= j:
            break
        if isPrime(n - j, PRIMES):
            bad = False
            n += 2
            break
    if bad:
        break

print(n)
コード例 #42
0
def generateNextA(previousVal, position):
    return previousVal + 2 * position


def generateNextB(previousVal, position):
    return previousVal + 4 * ((position + 1) // 2)


# represents the values with grid-size 1.
currA = 1
currB = 1
gridSize = 1
numPrimes = 0

while True:
    for i in range(2):  #grow both dimensions
        nextA, nextB = generateNextA(currA,
                                     gridSize), generateNextB(currB, gridSize)
        if isPrime(nextA):
            numPrimes += 1
        if isPrime(nextB):
            numPrimes += 1
        gridSize += 1
        currA, currB = nextA, nextB

    percentage = numPrimes * 100 / (gridSize // 2 * 4 + 1)

    if percentage < 10.0:
        print("{} grid size = {} primes. {}%".format(gridSize, numPrimes,
                                                     percentage))
        break
コード例 #43
0
from math import log
from math import sqrt
from euler import appendToPrimes
from euler import isPrime
from euler import appendDigitsUnsorted

N = 1000000  # N = 100 #
BASE = 10

primes = []
appendToPrimes(int(sqrt(N)), primes)
# print(primes) # [2, 3, 5, 7]

a = int(sqrt(N))
while a < N:
    if isPrime(a, primes):
        primes.append(a)
    a += 1

# primes contains all primes less than N.
# print(primes) # [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]

possibles = [
]  # potentially right truncatable: no internal {0,2,4,5,6,8} and no left {0,4,6,8}
for p in primes:
    digits = appendDigitsUnsorted(p, [])
    if 0 in digits or 4 in digits or 6 in digits or 8 in digits:
        continue
    digits.pop(0)
    if 2 in digits or 5 in digits:
        continue
コード例 #44
0
#
# How many circular primes are there below one million?
from euler import isPrime


# if there are even digits, skip it! one of the rotations will be even, therefore non prime.
def contains_even_digits(number):
    even_digits = set('24680')
    return any((d in even_digits) for d in str(number))


def find_rotations(number):
    as_str = str(number)
    result = [number]
    for i in range(0, len(as_str) - 1):
        rotation = as_str[1:] + as_str[:1]
        result.append(int(rotation))
        as_str = rotation
    return result


if __name__ == '__main__':
    UPPER_LIMIT = 1000000
    # skip 2, the only EVEN prime...
    number_found = 1  # conting 2
    for i in range(3, UPPER_LIMIT):
        if contains_even_digits(i):
            continue
        if all(isPrime(x) for x in find_rotations(i)):
            number_found += 1
    print(number_found)
コード例 #45
0
ファイル: 46.py プロジェクト: ArturoBlazquez/Project-Euler
from euler import isPrime, range_infinite, primes

primes = primes(10**5)

for i in range_infinite(35, 2):
    if not isPrime(i):
        flag = True
        for p in primes:
            if p < i:
                found = False
                for j in range_infinite(1, 1):
                    if p + 2 * j * j > i:
                        break
                    elif p + 2 * j * j == i:
                        found = True
                        break
                if found:
                    break
            else:
                flag = False
                break
        if not flag:
            print i
            break

#5777
コード例 #46
0
from euler import isPrime

curr = 1
diff = 2
primecount = 0
side = 1
while (primecount / (side * 2.0 - 1)) > 0.1 or primecount == 0:
    for k in range(4):
        curr = curr + diff
        if isPrime(curr):
            primecount += 1
    diff += 2
    side += 2

print side