Ejemplo n.º 1
0
def diagonal_sum():

    primes = 0
    not_primes = 0

    for i in range(1, 28000):

        top_right = ((2 * i)**2) - (2 * i) + 1
        top_left = ((2 * i)**2) + 1
        bottom_right = ((2 * i) - 1)**2
        bottom_left = (((2 * i) + 1)**2) - ((2 * i) + 1) + 1

        if is_prime(top_right):
            primes += 1
        else:
            not_primes += 1
        if is_prime(top_left):
            primes += 1
        else:
            not_primes += 1
        if is_prime(bottom_right):
            primes += 1
        else:
            not_primes += 1
        if is_prime(bottom_left):
            primes += 1
        else:
            not_primes += 1

        if primes / (not_primes + primes) <= 0.1:
            return 2 * i + 1
Ejemplo n.º 2
0
def is_family(f):
  for i in range(len(f)):
    for j in range(i + 1, len(f)):
      left = int_concat(f[i], f[j])
      right = int_concat(f[j], f[i])
      if not (is_prime(left) and is_prime(right)):
        return False
  return True
Ejemplo n.º 3
0
def is_truncatable_prime(number):
    if not is_prime(number):
        return False
    number = str(number)
    for x in range(1, len(number)):
        if not is_prime(int(number[:-x])) or not is_prime(int(number[x:])):
            return False
    return True
Ejemplo n.º 4
0
def test_goldbach(n):
    if n % 2 == 0 or helpers.is_prime(n):
        return True
    for i in itertools.count(1):
        k = n - 2 * i * i
        if k <= 0:
            return False
        elif helpers.is_prime(k):
            return True
Ejemplo n.º 5
0
def good_pair(a, b):
    key_pair = (a, b)
    if key_pair in pairmem:
        return pairmem[key_pair]
    stra = str(a)
    strb = str(b)
    result = is_prime(int(stra + strb)) \
         and is_prime(int(strb + stra))
    pairmem[key_pair] = result
    return result
Ejemplo n.º 6
0
Archivo: p60.py Proyecto: lukeleslie/pe
def get_concat_primes(i):
	prime = primes[i]
	prime_concats = set()
	for j in xrange(i+1, len(primes)):
		prime_j = primes[j]
		c1 = concat(prime, prime_j)
		c2 = concat(prime_j, prime)
		c1_prime = c1 in primes if c1 < limit else is_prime(c1)
		c2_prime = c2 in primes if c2 < limit else is_prime(c2)
		if c1_prime and c2_prime:
			prime_concats.add(j)
	return prime_concats
Ejemplo n.º 7
0
def is_truncatable_prime(n):
    # Left truncatable
    i = 10
    while i <= n:
        if not helpers.is_prime(n % i):
            return False
        i *= 10
    # Right truncatable
    while n > 0:
        if not helpers.is_prime(n):
            return False
        n //= 10
    return True
Ejemplo n.º 8
0
def get_more_primes():
    global working_combos, all_primes
    all_primes = get_prime_numbers_until(10000)
    all_primes.remove(2)
    all_primes.remove(5)
    for cur_prime in all_primes:
        for prime in list(working_combos.keys()):
            left = int(str(prime) + str(cur_prime))
            right = int(str(cur_prime) + str(prime))
            if is_prime(left) and is_prime(right):
                working_combos[prime].add(cur_prime)
                working_combos[cur_prime].add(prime)
        working_combos[cur_prime] = set()
Ejemplo n.º 9
0
def truncate_left(n):

    if not is_prime(n):
        return False
    else:
        i = str(n)
        while len(i) != 1:
            i = int(i[1:])
            if not is_prime(i):
                return False
            else:
                i = str(i)
                if len(i) == 1:
                    return True
Ejemplo n.º 10
0
def yield_circ_primes(limit):

    for i in range(3, limit):
        if is_prime(i):
            m = list(str(i))
            if rotate(m, i):
                yield i
Ejemplo n.º 11
0
def result(n):
    _max = 1
    _max_a = 1
    _max_b = 1
    first_primes = [j for j in range(n + 1) if is_prime(j)]
    for a in range(- n, n + 1):
        for b in first_primes:
            i = 0
            while is_prime(binome(a, b)(i)):
                i += 1
            if i >= _max:
                _max = i
                _max_a = a
                _max_b = b

    return _max_a * _max_b
Ejemplo n.º 12
0
def p50():
    primelist = list(primes(4000))
    for x in range(1,200):
        for y in range(x,-1,-1):
            s = sum(primelist[y:len(primelist)-(x-y)])
            if is_prime(s):
                return s
Ejemplo n.º 13
0
def eight_prime_family(prime, rd):
    c = 0
    for digit in '0123456789':
        n = int(str.replace(prime, rd, digit))
        if n > 100000 and is_prime(n):
            c += 1
    return c == 8
Ejemplo n.º 14
0
def largest_prime_factor(n=600851475143):
    """P3. Finds the largest prime factor of n."""
    for i in xrange(1, n, 2):
        if n % i == 0:
            # use its larger factor pair
            j = n // i
            if is_prime(j):
                return j
Ejemplo n.º 15
0
def solution1(n):
    """
    Slow solution. Performs primarly test in a range and checks
    if it is a factor of n, divides n by it, and repeats until
    factor of n is 1.
    """
    current = n
    max_factor = 1

    while not is_prime(current) and current > 1:
        for number in range(int(sqrt(current))):
            if is_prime(number) and current % number == 0:
                current = current / number
                if number > max_factor:
                    max_factor = number

    return max_factor
Ejemplo n.º 16
0
def p51():
    primelist = [p for p in primes(1000000) if p > 100001]
    for prime in primelist:
        for number_family in number_familes(prime):
            prime_family = [n for n in number_family if is_prime(n) and len(str(n)) == len(str(prime))]
            if len(prime_family) == 8 and prime in prime_family:
                print prime
                return
Ejemplo n.º 17
0
def prime_factors(num):
    """Get prime factors of a number
    My first attempt
    """
    prime_factors = []
    for i in range(2, num + 1):
        if (num % i) == 0 and is_prime(i) == True:
            prime_factors.append(i)
    return prime_factors
Ejemplo n.º 18
0
def problem7():
    """ The 10001st prime number"""
    primelist = [2, 3]
    i = 5
    while len(primelist) < 10001:
        if h.is_prime(i):
            primelist.append(i)
        i = i + 2  # increment by 2, to check odds only
    return primelist[-1]
Ejemplo n.º 19
0
Archivo: p58.py Proyecto: lukeleslie/pe
def answer(limit):
    num_primes = 0
    corner = 1
    for i in xrange(1, limit):
        side_length = 2 * i + 1
        for _ in xrange(4):
            corner = corner + side_length - 1
            num_primes += 1 if is_prime(corner) else 0
        if num_primes / (4.0 * i + 1.0) < 0.1:
            return side_length
Ejemplo n.º 20
0
def main():
    _len = 1
    nb_primes = 0
    ratio = 1
    nb_diag_number = 1
    while ratio > 0.1 or _len < 9:
        _len += 2
        _len2 = _len ** 2
        if is_prime(_len2):
            nb_primes += 1
        if is_prime(_len2 - (_len - 1)):
            nb_primes += 1
        if is_prime(_len2 - 2 * (_len - 1)):
            nb_primes += 1
        if is_prime(_len2 - 3 * (_len - 1)):
            nb_primes += 1
        nb_diag_number += 4
        ratio = nb_primes / nb_diag_number
    return _len
Ejemplo n.º 21
0
def compute(num_digits):

    # Option to lop off the start when using smaller pandigital numbers.
    num = '987654321'[9 - num_digits:]

    return list(
        islice(
            ("".join(digit)
             for digit in permutations(num) if is_prime(int("".join(digit)))),
            1))
Ejemplo n.º 22
0
def nth_prime(n):
  num = 1
  prime = 1
  prime_count = 0
  while prime_count <= n:
    if is_prime(num):
      prime = num
      prime_count += 1
    num += 2

  return prime
Ejemplo n.º 23
0
def try_prime(number):
    truncatable_primes = []
    if number > 9 and is_truncatable_prime(number):
        truncatable_primes.append(number)

    new_value = number * 10
    for digit in digits:
        new_prime = new_value + digit
        if is_prime(new_prime):
            truncatable_primes += try_prime(new_value + digit)
    return truncatable_primes
Ejemplo n.º 24
0
def compute(limit):

    n_max = 0

    for b in prime_sieve(limit):
        for a in range(-b, 0, 2):
            n = 1
            while m(n, a, b) > 0 and is_prime(m(n, a, b)):
                n += 1
            if n > n_max:
                n_max, prod = n, a * b
    return prod
Ejemplo n.º 25
0
def nth_prime1(n):
    """
    Loop through numbers and use trial division for primarly test, 
    keep count of which ones are prime, return the nth prime.
    """
    count = 0
    current = 1
    while count < n:
        current += 1
        if is_prime(current):
            count += 1
    return current
Ejemplo n.º 26
0
def rotate(m, n):

    c = 0
    while n != c:
        end = m[1:]
        end.append(m[0])
        whole = ''.join(end)
        c = int(whole)
        if not is_prime(c):
            return False
        m = list(str(whole))
    return True
Ejemplo n.º 27
0
def compute():
    # Note: The only 1-digit pandigital number is 1, which is not prime. Thus we require n >= 2.
    for n in reversed(range(2, 10)):
        arr = list(reversed(range(1, n + 1)))
        while True:
            if arr[-1] not in NONPRIME_LAST_DIGITS:
                n = int("".join(str(x) for x in arr))
                if helpers.is_prime(n):
                    return str(n)
            if not prev_permutation(arr):
                break
    raise AssertionError()
Ejemplo n.º 28
0
Archivo: p41.py Proyecto: lukeleslie/pe
def answer(n):
    # could speed up by iterating backwards in a permutation
    trunc = pan[:n]
    permutations = itertools.permutations(trunc)
    max_val = 0
    for p in permutations:
        p_str = "".join(p)
        val = int(p_str)
        if is_prime(val) and is_pandigital(p_str):
            max_val = max(max_val, val)
    if max_val != 0:
        return max_val
    return answer(n - 1)
Ejemplo n.º 29
0
def problem3(N=600851475143):
    """What is the largest prime factor of the number N = 600851475143 ?

    This solution will make use of the fact that a number is prime if it
    has no prime factors smaller than sqrt(n). Potential factors are checked
    from high to low, decrementing by 2 because N is not even.
    """
    check_factor = int(sqrt(N))
    while True:
        if h.divisible(N,check_factor) and h.is_prime(check_factor):
            return check_factor
        else:
            check_factor -= 1
Ejemplo n.º 30
0
def get_prime_factors(number):
    """Return all prime factors which must be multiplied
    to generate a certain number
    """
    factors_list = []
    for j in range(2, number + 1):
        while True:
            if is_factor(number, j) and is_prime(j):
                factors_list.append(j)
                number = number // j
            else:
                break
    return factors_list
Ejemplo n.º 31
0
def truncate_right(n):

    j = str(n)
    while len(j) != 1:
        j = int(j[:-1])
        if not is_prime(j):
            return False
        else:
            j = str(j)
            if len(j) == 1:
                return True
    else:
        return False
Ejemplo n.º 32
0
def problem03():
    """
    Q: What is the largest prime factor of the number 600851475143?
    A: 6857
    """
    n = 600851475143
    factors = helpers.get_factors(n)
    largest = 0
    for factor in factors:
        if factor != n and factor > largest and helpers.is_prime(factor):
            largest = factor

    return largest
Ejemplo n.º 33
0
def main():
    # combinations of prime under 100 that are prime. 2, 3, 5 and 7 are skipped
    truncatable_primes = [23, 37, 53, 73]

    n = 101
    offset = 1

    while len(truncatable_primes) < 11:
        # alternative to use accumulate([2, 1, 2], cycle([2, 4]))
        n += 3 - offset  # 2 or 4
        offset *= -1

        # all truncatables number above 100 cannot contains even digits or 5
        if not re.search('[245680]', str(n)) and is_prime(n) and is_truncatable_prime(n):
            truncatable_primes.append(n)
    return sum(truncatable_primes)
Ejemplo n.º 34
0
def phi2(num):
    # print [i for i in range(2,num) if areRelativePrime(num , i)]
    if helpers.is_prime(num):
        return -1
    global maxPhi
    phi_num = 1
    phi_cache = []
    for i in range(2, num):
        for j in phi_cache:
            if i % j == 0:
                break
        else:
            if helpers.are_relative_prime(num, i):
                phi_num += 1
                if (num / phi_num) <= maxPhi:
                    return -1
            else:
                phi_cache.append(i)
    return phi_num
Ejemplo n.º 35
0
def find_prime_ratio(required_ratio, upper_bound):
    s = 1
    prime_count = 0

    primes = primes_up_to(upper_bound)

    for diagonals in get_diagonals():

        for d in diagonals:
            if d > upper_bound:
                if is_prime(d, cache_result=False):
                    prime_count += 1
            elif d in primes:
                prime_count += 1

        ratio = (prime_count / float(s * 4))
        if ratio < required_ratio:
            return (2 * s) + 1

        s += 1
Ejemplo n.º 36
0
def main():
    list_primes = list(eratosthene(1000000))

    for prime in list_primes:
        if prime < 100000:
            continue

        dict_count = get_digit_count_dict(prime)
        for _str in ['0', '1', '2']:
            if dict_count[_str] >= 3:
                size = 0
                error = 0
                # replace all numbers
                mask = str(prime).replace(_str, '.')
                for other_digit in range(int(_str), 10):
                    if error > 3:
                        break
                    if is_prime(int(mask.replace('.', str(other_digit)))):
                        size += 1
                    else:
                        error += 1
                if size == 8:
                    return prime
Ejemplo n.º 37
0
def compute(limit):

    for k in range(limit):
        if is_prime(k) and truncate_left(k) and truncate_right(k):
            yield k
Ejemplo n.º 38
0
import time, math, helpers

start = time.clock()

primecount = 0
totcount = 1

num = 1
for i in range(2, 100000, 2):
  for j in range(4):
    if helpers.is_prime(num):
      primecount += 1
    totcount += 1
    num += i
  if float(primecount)/float(totcount)<0.10:
    print i+1
    print time.clock()-start
    quit()
Ejemplo n.º 39
0
def is_harshad(num):
    if num < 10 or num in hasdasdfs:
        return True
    if num in not_hasss:
        return False
    if num % sum([int(i) for i in str(num)]) == 0:
        return is_harshad(num // 10)
    return False


num = 1
hazards = {0: [1, 2, 3, 4, 5, 6, 7, 8, 9]}
results = []
for k in range(0, 12):
    hazards[k + 1] = []
    for h in hazards[k]:
        h *= 10
        for i in range(0, 10):
            hi = h + i
            if is_harshad(hi):
                hazards[k + 1].append(hi)
                if helpers.is_prime(hi / sum([int(ii) for ii in str(hi)])):
                    for p in range(0, 10):
                        the_num = hi * 10 + p
                        if helpers.is_prime(the_num):
                            results.append(the_num)
                    # print("\033[0;35mi", hi, "\033[0m")

print("\033[0;35msum(results)", sum(results), "\033[0m")
print(time.clock() - start_time)
Ejemplo n.º 40
0
def concat(i,j):
  if not is_prime(int(str(i)+str(j))) or not is_prime(int(str(j)+str(i))):
     return False
  return True
Ejemplo n.º 41
0
def is_truncatable_prime(n):
    for d in range(1, len(str(n))):
        if not is_prime(int(str(n)[d:])) or not is_prime(int(str(n)[:d])):
            return False
    return True
Ejemplo n.º 42
0
def solution():
    total = 0
    for num in range(LIMIT):
        if is_prime(num):
            total += num
    return total
Ejemplo n.º 43
0
'''
Created on Jan 9, 2017

@author: jfinn
'''
from helpers import is_prime
from _functools import reduce
import operator

primes = [2]
for n in range(3, 2000000):
    if is_prime(n, primes):
        primes.append(n)

print("Found", len(primes), "primes below 2,000,000")
print(reduce(operator.add, primes))
Ejemplo n.º 44
0
#!env/bin/python

import helpers as h

c = 0
x = 23
r = 0

while c < 11:
    while not h.is_prime(x):
        x += 2
    for ch in str(x):
        if int(ch) % 2 == 0 and ch != '2':
            x += 2
    number = x
    skip = False
    while number > 0:
        if not h.is_prime(number):
            skip = True
            break
        number /= 10
    if skip:
        x += 2
        continue
    number = x % (10**int(h.log10(x)))
    while number > 0:
        if not h.is_prime(number):
            skip = True
            break
        number = number % (10**int(h.log10(number)))
    if skip:
Ejemplo n.º 45
0
#!env/bin/python

import helpers as h

MAX = 1000
bl = -1
ba = 0
bb = 0
br = -1
for a in range(-1*MAX,MAX+1):
    for b in range(-1*MAX+1,MAX+1,2):
        if not h.is_prime(b):
            continue
        i = 0
        r = (i*i)+(a*i)+b
        pr = 0
        while h.is_prime(r):
            i += 1
            r = (i*i)+(a*i)+b
        if i >= bl:
            bl = i
            ba = a
            bb = b

print 'n = 0 to '+str(bl)
print 'a = '+str(ba)
print 'b = '+str(bb)
Ejemplo n.º 46
0
def a_n(n):
  if n == 1: return 0
  elif is_prime(n): return 1
  else: return 0
Ejemplo n.º 47
0
#!env/bin/python

import helpers as h

def list_to_num(n):
    s = ''
    for x in n:
        s = s + str(x)
    return int(s)

result = None
s = [10,9,8,7,6,5,4,3,2,1]
while result == None:
    s.pop(0)
    t = 0
    for x in s:
        t += x
    if t % 3 == 0:
        continue
    for x in h.permute(s):
        if x[len(s)-1] % 2 == 0:
            continue
        if h.is_prime(list_to_num(x)):
            result = x
            break
    print s

print result
Ejemplo n.º 48
0
def concat(lijst):
    for i, j in combinations(lijst, 2):
        if not is_prime(int(str(i) + str(j))) or not is_prime(
                int(str(j) + str(i))):
            return False
    return True
Ejemplo n.º 49
0
from helpers import sieve, is_prime

p = sieve(10000)

total = 0
start = 0
length = 0
maxlen = 0
while True:
    if total + p[start + length] < 1000000:
        total += p[start + length]
        length += 1
        if length > maxlen and is_prime(total):
            if 1000000 - total < p[start + length]:
                print total
                break
            maxlen = length
    else:
        total -= (p[start] + p[start + length - 1])
        length -= 2
        start += 1
Ejemplo n.º 50
0
 def get_prime_factors(num):
     """Returns the prime factors for num."""
     for i in xrange(2, num):
         if num % i == 0 and is_prime(i):
             yield i
Ejemplo n.º 51
0
def prime_factors(number):
    """A better version utilizing reduce to compute
    the factors
    """
    all_factors = factors(number)
    return list(filter(lambda x: is_prime(x), all_factors))
Ejemplo n.º 52
0
from helpers import is_prime

size = 1
value = 1

total = 1
primes = 0
while True:
    size += 2

    top_right_value = value + size - 1
    top_left_value = top_right_value + size - 1
    bottom_left_value = top_left_value + size - 1
    bottom_right_value = bottom_left_value + size - 1
    value = bottom_right_value

    if is_prime(top_right_value):
        primes += 1
    if is_prime(top_left_value):
        primes += 1
    if is_prime(bottom_left_value):
        primes += 1
    if is_prime(bottom_right_value):
        primes += 1
    total += 4

    if primes / total < 0.1:
        break

print(size)
Ejemplo n.º 53
0
# This is really dumb and takes forever to run, I know
# A smarter way would just check random combos matching ([3,7,9][1,3,7,9]*[3,7,9]) until you find 11
from helpers import sieve, is_prime
print sum([int(p) for p in map(str,sieve(1000000)[4:]) if all([is_prime(int(p[i:])) and is_prime(int(p[:i+1])) for i in range(len(p))])])
Ejemplo n.º 54
0
def main():
  filtered = [i for i in range(3, NUMBER, 2)]
  print (2 + sum(i for i in filtered if is_prime(i)))
Ejemplo n.º 55
0
 def jamcoin_has_prime_base(self, jamcoin_bases):
     print jamcoin_bases
     return [base for base in jamcoin_bases if helpers.is_prime(base)]
Ejemplo n.º 56
0
'''
Created on Jan 22, 2017

@author: jfinn
'''
from helpers import is_prime

primes = [2]
for num in range(3, 1000000):
    if is_prime(num):
        primes.append(num)

primes = set(primes)  # faster lookup

circ_primes = []
num_circ = 0
for prime in primes:
    is_circ_prime = True
    num_digits = len(str(prime))
    num = prime
    for i in range(num_digits):
        if num not in primes:
            is_circ_prime = False
            break
        ones = num % 10
        num = (num // 10) + (ones * 10**(num_digits - 1))
    if is_circ_prime:
        num_circ += 1
        circ_primes.append(prime)

print(circ_primes)