예제 #1
3
def s(p,S):
	'''return the number of primes when we replace all letters at positions
	corresponding to the set S '''
	sp=str(p)
	count = 0
	for s in S:
		if sp[s]!=sp[S[0]]:return -1
		
	if 0 in S: lower=1
	else: lower=0	
	
	for i in range(lower,10):
		sp1=""
		for j in range(0,len(sp)):
			if j in S: sp1 += str(i)
			else: sp1+=sp[j]
		if functions.isPrime(int(sp1))	:
			# print sp1
			count +=1
	return count
예제 #2
2
import functions as funcs
from time import time

primes1 = [x**2 for x in range(2, 7071) if funcs.isPrime(x)]
primes2 = [x**3 for x in range(2, 368) if funcs.isPrime(x)]
primes3 = [x**4 for x in range(2, 84) if funcs.isPrime(x)]

ctr = []

for i in primes1:
    # if i % 1000 == 0:
    #     print i
    for j in primes2:
        for k in primes3:
            num = i + j + k
            if num >= 50000000:
                break
            ctr.append(num)            #
            # else:
            #     if num not in ctr:
            #         ctr.append(num)
a = time()
len(ctr)
print time() - a
a = time()
len(set(ctr))
print time() - a
a = time()
set(ctr).__len__()
print time() - a
예제 #3
1
파일: main.py 프로젝트: elitan/euler
def circularPrime(p):
	if '0' in str(p):
		return False

	for n in range(0, len(str(p))-1):
		p = nextCircularNumber(p)
		if not f.isPrime(p):
			return False

	return True
예제 #4
1
파일: main.py 프로젝트: elitan/euler
40 19  6  1  2 11 28
41 20  7  8  9 10 27
42 21 22 23 24 25 26
43 44 45 46 47 48 49

It is interesting to note that the odd squares lie along the bottom right diagonal, but what is more interesting is that 8 out of the 13 numbers lying along both diagonals are prime; that is, a ratio of 8/13 ≈ 62%.

If one complete new layer is wrapped around the spiral above, a square spiral with side length 9 will be formed. If this process is continued, what is the side length of the square spiral for which the ratio of primes along both diagonals first falls below 10%?
"""

import sys
sys.path.append("../")
import functions as f

primes = 0
nonePrimes = 1
ac = 1
p = 1
i = 0
while p > 0.1:
	ac += 2
	i += 1
	a = pow(ac, 2)
	for j in range(0,4):
		n = a-(i*2)*j
		if f.isPrime(n):
			primes += 1
		else:
			nonePrimes += 1
	p = primes / (nonePrimes+primes)
print(ac)
예제 #5
0
파일: main.py 프로젝트: elitan/euler
def isPrimePairs(p, q):
	n = int(str(p) + str(q))
	m = int(str(q) + str(p))
	
	if not f.isPrime(n) or not f.isPrime(m):
		return False;
	return True
예제 #6
0
def check(n):
    n_str = str(n)
    for i in range(len(n_str)):
        if not isPrime(int(n_str[i:len(n_str)])):
            return False
    for i in range(1, len(n_str)):
        if not isPrime(int(n_str[0:i])):
            return False
    return True
예제 #7
0
def truncatable(p):
    s = str(p)
    while p > 0:
        if p > 2 and p % 2 == 0:
            return False
        p //= 10

    if any(not isPrime(int(s[i:])) for i in range(0, len(s))):
        return False

    if any(not isPrime(int(s[:i])) for i in range(len(s), 0, -1)):
        return False

    return True
예제 #8
0
def fillP():
	count, t = 0,2
	while count < numberPrimes:
		if isPrime(t):
			P.append(t)
			count +=1
		t+=1	
예제 #9
0
def main():
    start = t.time()
    i = 9
    while True:
        if not f.isPrime(i) and not isComposite(i):
            print(f"Found the answer, it is {i}")
            print(f"This took {t.time() - start} seconds to run.")
            return
        i += 2
예제 #10
0
def main():
    i = 9
    while True:
        if not isPrime(i):
            if not goldbach_split(i):
                print('-------->', i, '<--------')
                break
            else:
                print(i)
        i += 2
예제 #11
0
def main():

    num = 2
    index = 1
    while True:
        if isPrime(num):
            print(index, '-->', num)
            index += 1
        if index == 10002:
            break
        num += 1
예제 #12
0
    def countPrime(self):

        count = 0
        ptr = self.head

        while ptr != None:

            if isPrime(ptr.data):

                count += 1

            ptr = ptr.next

        return count
예제 #13
0
def euler58():
	i = 7
	while True:
		c = 0
		d = diagonals(i)
		for j in d:
			if isPrime(j):
				c+=1
		per = 100.0*(c/(i*2-1))
		print(f'{i}: {per}')
		if per<10:
			print(f'-->{i}<--')
		print(i)
		i+=2
예제 #14
0
def main():
    start = t.time()
    for n in range(1000, 10000):
        if badNum(n):
            continue
        pg = f.permuteGen(n)
        primes = []
        for i in range(24):
            perm = next(pg)
            if f.isPrime(int(perm)):
                primes.append(int(perm))
        primes = set(primes)
        if len(primes) >= 3 and 1487 not in primes and equiSpaced(primes):
            print(f"This took {t.time() - start} seconds to run.")
            return
        primes.clear()
예제 #15
0
def euler58_():
	lst = [3,5,7]
	c = 3
	for i in range(5,30001,2):
		a = lst[-3]+(len(lst)//3*8+2)
		b = len(lst)//3+1
		lst.extend([a,a+2*b,a+4*b])
		c+=len([
			i
			for i in [a,a+2*b,a+4*b]
			if isPrime(i)
		])
		if (c/(i*2-1))<0.1:
			print(f'-->{i}<--')
			break
		print(i)
예제 #16
0
def main():
    num_diags = 1  # start with 1 cuz 1 is in the middle
    num_primes = 0
    side_len = 2
    curr = 1
    while True:
        for i in range(4):
            curr += side_len
            num_diags += 1
            if f.isPrime(curr):
                num_primes += 1
            if num_primes / num_diags < 0.1:
                print(f"answer is {side_len+1}")
                return side_len
        side_len += 2

    print(f"num diags is {num_diags}")
    print(f"num primes is {num_primes}")
예제 #17
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?
"""
from functions import isPrime

arr = []
i = 1
while len(arr) < 10001:
    if isPrime(i):
        arr.append(i)
    i += 1

print(arr.pop())
예제 #18
0
from functions import isPrime
P = []
for a in range(2,400):
	if isPrime(a): P.append(a)
print P	

def smallestPrime(pN):
	'''return the smallest prime divisor of pN'''
	for p in P:
		if pN % p == 0:
			return p
	return pN
			
limit = 10**5
L = [0,1] #L[n] = rad(n) 			
def fillL():
	n = 1
	while n < limit:
		n+=1
		p = smallestPrime(n) 
		t = n/p
		# print n,p,t
		if t % p == 0:
			L.append(L[t])
		else:	
			L.append(L[t]*p)
	print 'L is filled'
fillL()			
def test():
	for i in range(limit)	:
		# print i,L[i]
    return True


def no0(n):
    return str(n).count("0") == 0


primes = list(i for i in primesUnder(10000) if noRepeats(i) and no0(i))

total = 0
for i in primes:
    digits = "123456789"
    for j in str(i):
        digits = digits.replace(j, "")
    for j in ["".join(p) for p in permutations(digits)]:
        if isPrime(int(j)):
            total += 1
            print(i, int(j), total)

for i in range(len(primes) - 1):
    for j in range(i + 1, len(primes)):
        digits = "123456789"
        p1 = primes[i]
        p2 = primes[j]
        digitCounts = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        valid = True
        for k in str(p1) + str(p2):
            digitCounts[int(k)] += 1
            if max(digitCounts) > 1:
                valid = False
                break
예제 #20
0
def main():
    n = 0
    for i in range(1, int(600851475143**(1 / 2)) + 1):
        if isPrime(i) and 600851475143 % i == 0:
            print(i)
예제 #21
0
from functions import isPrime, primeSieve

n=1000

#list all the primes up to n
primeList=primeSieve(n)
maxNumber=0

# a and b have a range of abs(a) and abs(b) < 1000
# this means we have to go from -999 to 999
for a in range(-n, n, 1):
	for b in primeList:
		x=1
		while isPrime(x**2 + a*x + b):
			x+=1
		if x>maxNumber:
			maxNumber=x
			prime=a*b

print "Project Euler - Problem 27"
print "Quadratic Primes Answer : ",prime
예제 #22
0
파일: main.py 프로젝트: elitan/euler
	return newN


pl = f.primeList(1000000)
low = 999999999

for p in pl:
	#print("Testing prime: %d" % p)
	for i in range(1, len(str(p))):
		lists = perm(i, p)
		for l in lists:
			#print("### %d ###" % p)
			c = 0
			cc = 0
			for j in range(0,10):
				cc += 1
				#print(j,l,p)
				primeTest = replace(j,l,p)
				if len(str(primeTest)) == len(str(p)) and f.isPrime(primeTest):
					c += 1
					#	print("%d:%d. Prime found: %d" % (c, cc, replace(j,l,p)))
				if cc-c > 2:
					break
			if c == 8:
				#print("PRIME: %d, nr: %d" % (p, c))
				for j in range(0,10):
					#print(j,l,p)
					primeTest = replace(j,l,p)
					if f.isPrime(primeTest):
						print(primeTest)
						exit(0)		
예제 #23
0
파일: main.py 프로젝트: elitan/euler
#!/bin/py

"""
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 sys
sys.path.append("../")
import functions as f
import itertools

t = 0
n = list("1")

while len(n) < 10:
	perm = itertools.permutations(n)

	for nr in perm:
		t = int(''.join(map(str,nr)))
		if f.isPrime(t):
			answer = t
	n.append(len(n)+1)

print(answer)
예제 #24
0
import math
import functions


# Modules in Python contains a list of related functions.
# In Python, import can import a module. For example, math is a module.
# Importing math module allows Python program to use various functions and variables in it.

print(math.sqrt(81)) # sqrt returns square root of a number
print(math.pi) # prints value of variable pi in math module
print(math.sin(math.radians(30))) # Returns sine value of x. x must be in radians. radians() converts degrees to radians

# Python files of same project can also be imported.
print(functions.isPrime(23))
# Note the output of functions is printed when you import functions.
# Python runs the imported modules when import runs.
# Make sure not to import unused modules.

import os

print(os.getcwd())
# import can be used anywhere in program. But, it is recommended to import at the top of program to avoid any confusion.
예제 #25
0
def subPrimes(p):
    out = []
    for i in subString(str(p)):
        if isPrime(int(i)):
            out.append(int(i))
    return out
예제 #26
0
# There are thirteen such primes below
# 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
#
# How many circular primes are there below one million?
from functions import isPrime
import itertools
import string


def rotate(string):
    x = string[1:]
    y = string[:1]
    return x + y


count = 1
for x in range(3, 1000000):
    if isPrime(x):
        length = len(str(x))
        prime = True
        a = str(x)
        for i in range(1, length):
            a = rotate(a)
            if not isPrime(int(a)):
                prime = False
        if prime:
            print x
            count += 1
print "Project Euler"
print "Answer to Problem 35 : ", count
예제 #27
0
파일: main.py 프로젝트: elitan/euler
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?
"""

import sys
sys.path.append("../")
sys.stdout.flush()
import functions as f

limit = 1000000
pl = f.primeList(limit)
t = []

i = 0
j = 0
mL = 0
mV = 0

for i in range(0, len(pl)):
	for j in range(i+1, len(pl)):
		s = sum(pl[i:j])
		if s > limit:
			break
		if f.isPrime(s) and s < limit and j-i > mL:
			t.append(sum(pl[i:j]))
			mL = j-i
			mV = sum(pl[i:j])
print(mL)
print(mV)	#answer
예제 #28
0
def test(n):
    for j in range(1, int(sqrt(n / 2)) + 1):
        val = n - 2 * pow(j, 2)
        if isPrime(val):
            return True
    return False
    for j in range(10):
        add = 0
        for x in range(7):
            if segments[i][x] == "1" and segments[j][x] == "1":
                add += 1
        new.append(add)
    common.append(new)


def difference(n):
    r = 0
    lastNum = n
    x = digitSum(n)
    while len(str(lastNum)) > 1:
        temp = str(lastNum)
        temp = temp[0 - len(str(x)):]
        for a in range(len(temp)):
            r += common[int(str(x)[a])][int(temp[a])] * 2
        lastNum = x
        x = digitSum(x)
    return r


tot = 0

for a in range(10**7 + 1, 2 * 10**7, 2):
    if isPrime(a):
        d = difference(a)
        tot += d
        print(a, d, tot)
print(tot)
예제 #30
0
def isCircularPrime(n):
	n = str(n)
	for start in range(len(n)):
		if not isPrime(int(n[start:len(n)]+n[0:start])):
			return False
	return True
예제 #31
0
파일: main.py 프로젝트: elitan/euler
n² + an + b, where |a| < 1000 and |b| < 1000

where |n| is the modulus/absolute value of n
e.g. |11| = 11 and |−4| = 4
Find the product of the coefficients, a and b, for the quadratic expression that produces the maximum number of primes for consecutive values of n, starting with n = 0.
"""

import sys
sys.path.append("../")
import functions as f
import math as m

answer = [0, 0, 0]

for a in range(-1000, 1000):
	for b in range(-1000, 1000):
		n = 0
		while f.isPrime(m.pow(n,2) + a*n + b):
			n += 1

		if n > answer[2]:
			answer = (a, b, n)

print(answer[0] * answer[1])





예제 #32
0
    return True


def subString(s):
    n = len(s)
    out = set()
    for Len in range(1, n + 1):
        for i in range(n - Len + 1):
            j = i + Len - 1
            sub = ''
            for k in range(i, j + 1):
                sub += s[k]
            out.add(sub)
    return out


def subPrimes(p):
    out = []
    for i in subString(str(p)):
        if isPrime(int(i)):
            out.append(int(i))
    return out


for i in range(1, 100000, 2):
    if len(subPrimes(i)) > 4:
        if all(isPrime(n[0]) for n in getPermutations(subPrimes(i))):
            print(i)
            print(sum(subPrimes(i)))
            print()
예제 #33
0
def fillP():
	'''filling P'''
	for i in range(2,limit):
		if functions.isPrime(i):
			P.append(i)
	print "filling P complete"	
예제 #34
0
def fillP():
	for i in range(2,limit2):
		if functions.isPrime(i):
			P.append(i)
	print 'P is filled', len(P)
예제 #35
0
from functions import sieve, isPrime
primes = sieve(1000)[1:]


def sum_of_digits(n):
    return sum([int(i) for i in str(n)])


for idx, i in enumerate(primes):
    # if idx == 1:
    # 	break
    s = set()
    for j in primes:
        if isPrime(int(str(j) + str(i))) and isPrime(int(str(i) + str(j))):
            s.add(j)
    print(s)
    # s = set([j for j in primes if isPrime(int(str(j)+str(i))) and isPrime(int(str(i)+str(j)))])

    # s = set(lst)
    # print(lst)
    # for j in s:
    # 	if len(set([k for k in primes if isPrime(int(str(k)+str(j))) and isPrime(int(str(j)+str(k)))]))>len(lst):
    # 		lst = [j]+[k for k in primes if isPrime(int(str(k)+str(j))) and isPrime(int(str(j)+str(k)))]
예제 #36
0
def fillP()	:
	for i in range(2, 10**3):
		if functions.isPrime(i): P.append(i)
	print 'P is filled'
예제 #37
0
def main():
    for i in range(10001, 10000000, 2):
        if not same_digits(i) and i % 10 != 0:
            if isPrime(i) and isPadnigital(i):
                print(i)
예제 #38
0
    n = str(n)
    for i in range(1, len(n)):
        if direction == 'r':
            r.append(int(n[:-i]))
        elif direction == 'l':
            r.append(int(n[i:]))
        elif direction == 'b':
            r.append(int(n[i:]))
            r.append(int(n[:-i]))

    return r


solution = 0

primes = file('Primzahlen.txt', 'r')

count = 11
for n_ in primes:
    n = int(n_[:-1])
    if n < 10:
        continue
    if all([isPrime(i) for i in truncatable(n, 'b')]):
        print n
        solution += n
        count -= 1
    if count == 0:
        break

print(solution)
예제 #39
0
def find_ns(a, b):
    n = 0
    while isPrime(n**2 + a * n + b):
        n += 1
    return n