Ejemplo n.º 1
0
def solve(seq=3):
    pr = sieve(10000).difference(sieve(1000))
    pr = sorted(pr)
    d = defaultdict(list)
    for p in pr:
        s = set(str(p))
        d[''.join(sorted(s))].append(p)
    for k, v in d.items():
        if len(v) > seq:
            check(v, seq)
Ejemplo n.º 2
0
def test ( ):
    n = 10
    if 2==ac:
        n = int(av[1])
    sv = sieve(100)
    t = sv.totient(n)
    print("phi(%d) = %d" % (n,t))
Ejemplo n.º 3
0
def proj_old ( ):
    s = sieve(10000)
    #write_primes(s)
    cnt = 0
    mn_list = []
    for p in s.plist:
        if p<1000:
            continue
        if p>10000:
            break
        strp = str(p)
        if '0' in strp:
            continue
        pm = perms(p,s)
        if 3==len(pm):
            pm.sort()
            pm_str = str(pm[0]) + str(pm[1]) + str(pm[2])
            if pm_str not in mn_list:
                mn_list.append(pm_str)
    for pm in mn_list:
        x1, x2, x3 = (int(pm[:4]),int(pm[4:8]),int(pm[8:]))
        d1 = x2 - x1
        d2 = x3 - x2
        if d1==d2:
            print("    This one:")
        print("%d %d %d, %4d %4d" % (x1, x2, x3, d1, d2))
Ejemplo n.º 4
0
 def get(self):
     for i in range(5, self.limit + 1):
         print(i)
         self.prime_list = primes.sieve(self.current_fib)
         self.res += self.function(self.current_fib, 1,
                                   len(self.prime_list) - 1)
         self.previous_fib, self.current_fib = self.current_fib, self.previous_fib + self.current_fib
Ejemplo n.º 5
0
def find_prime_group(target_size):
    length = 1
    while True:
        length += 1
        primes = map(str, sieve(10**length))
        n_length_primes = set(filter(lambda x: len(x) == length, primes))
        for count in range(1, length):
            for choices in get_choices(range(0, length), count):
                digits = "0123456789"
                if 0 in choices:
                    digits = "123456789"
                if length-1 in choices:
                    digits = "1379"
                for p in n_length_primes:
                    result = []
                    for d in digits:
                        candidate = ''
                        for i in range(0, length):
                            if i in choices:
                                candidate += d
                            else:
                                candidate += p[i]
                        if candidate in n_length_primes:
                            result.append(candidate)
                    if len(result) == target_size:
                        return result
Ejemplo n.º 6
0
def test():
    n = 10
    if 2 == ac:
        n = int(av[1])
    sv = sieve(100)
    t = sv.totient(n)
    print("phi(%d) = %d" % (n, t))
Ejemplo n.º 7
0
def proj_old():
    s = sieve(10000)
    #write_primes(s)
    cnt = 0
    mn_list = []
    for p in s.plist:
        if p < 1000:
            continue
        if p > 10000:
            break
        strp = str(p)
        if '0' in strp:
            continue
        pm = perms(p, s)
        if 3 == len(pm):
            pm.sort()
            pm_str = str(pm[0]) + str(pm[1]) + str(pm[2])
            if pm_str not in mn_list:
                mn_list.append(pm_str)
    for pm in mn_list:
        x1, x2, x3 = (int(pm[:4]), int(pm[4:8]), int(pm[8:]))
        d1 = x2 - x1
        d2 = x3 - x2
        if d1 == d2:
            print("    This one:")
        print("%d %d %d, %4d %4d" % (x1, x2, x3, d1, d2))
Ejemplo n.º 8
0
def find_prime_group(target_size):
    length = 1
    while True:
        length += 1
        primes = map(str, sieve(10**length))
        n_length_primes = set(filter(lambda x: len(x) == length, primes))
        for count in range(1, length):
            for choices in get_choices(range(0, length), count):
                digits = "0123456789"
                if 0 in choices:
                    digits = "123456789"
                if length - 1 in choices:
                    digits = "1379"
                for p in n_length_primes:
                    result = []
                    for d in digits:
                        candidate = ''
                        for i in range(0, length):
                            if i in choices:
                                candidate += d
                            else:
                                candidate += p[i]
                        if candidate in n_length_primes:
                            result.append(candidate)
                    if len(result) == target_size:
                        return result
Ejemplo n.º 9
0
 def __init__(self, maxElem: int, fillFactorTree=False):
     self.maxElem = maxElem
     self.primes = sieve(maxElem)
     self._factors = {prime: Counter([prime]) for prime in self.primes}
     self._factors[1] = Counter([1])
     self.filledFactorTree = fillFactorTree
     if fillFactorTree:
         self.fill_factor_tree()
     return None
Ejemplo n.º 10
0
def find():
    p = sieve(10000)
    for n in xrange(1488, 10000):
        for s in xrange(1, (10000 - n) / 2):
            d1 = digits_of(n)
            d2 = digits_of(n + s)
            d3 = digits_of(n + 2 * s)
            if d1 == d2 and d2 == d3 and \
                    is_sieve_prime(p, n) and is_sieve_prime(p, n + s) and is_sieve_prime(p, n + 2 * s):
                print str(n) + str(n + s) + str(n + 2 * s)
                return
Ejemplo n.º 11
0
def proj():
    sv = sieve(10000)
    print("Starting")
    start = 2
    end = 10**6
    tot = 0
    for n in range(start, end+1):
        sys.stdout.write("n = %d\r" % n)
        totn = sv.totient(n)
        tot = tot + totn
        
    print("")
    print("tot = %d" % (tot))
Ejemplo n.º 12
0
def proj():
    sv = sieve(10000)
    print("Starting")
    start = 2
    end = 10**6
    tot = 0
    for n in range(start, end + 1):
        sys.stdout.write("n = %d\r" % n)
        totn = sv.totient(n)
        tot = tot + totn

    print("")
    print("tot = %d" % (tot))
Ejemplo n.º 13
0
def proj():
    s = sieve(10000)
    not_found = True
    for p in s.plist:
        if p < 1400:
            continue
        if p >= 10000:
            break
        b, c = p + 3330, p + 6660
        if s.is_prime(b) and s.is_prime(c) and is_perm(p, b) and is_perm(p, c):
            not_found = False
            print("%d %d %d" % (p, b, c))
            print("    %d%d%d" % (p, b, c))
    if not_found:
        print("Nothing found")
Ejemplo n.º 14
0
def proj():
    s = sieve(10000)
    not_found = True
    for p in s.plist:
        if p<1400:
            continue
        if p>=10000:
            break
        b, c = p+3330, p+6660
        if s.is_prime(b) and s.is_prime(c) and is_perm(p,b) and is_perm(p,c):
            not_found = False
            print("%d %d %d" % (p,b,c))
            print("    %d%d%d" % (p,b,c))
    if not_found:
        print("Nothing found")
Ejemplo n.º 15
0
def proj():
    sv = sieve(10000)
    nmx = 1000000
    mx = 0

    print("Starting")
    for n in range(2, nmx + 1):
        sys.stdout.write("n = %d\r" % n)
        ratio = float(n) / float(sv.totient(n))
        if ratio > mx:
            mx = ratio
            mxn = n

    print("")
    print("%d results in ratio %f" % (mxn, mx))
Ejemplo n.º 16
0
def proj():
    sv = sieve(10000)
    nmx = 1000000
    mx = 0

    print("Starting")
    for n in range(2,nmx+1):
        sys.stdout.write("n = %d\r" % n)
        ratio = float(n)/float(sv.totient(n))
        if ratio>mx:
            mx = ratio
            mxn = n
    
    print("")
    print("%d results in ratio %f" % (mxn,mx))
Ejemplo n.º 17
0
def proj():
    idx = 2
    x = 1
    mx = 100000
    s = sieve(mx)
    tot, pcnt = 1, 0
    stop = False
    while not stop:
        for k in range(4):
            x = x + idx
            tot = tot + 1
            if s.is_prime(x):
                pcnt = pcnt + 1
            p = float(pcnt) / float(tot)
            if p < 0.1:
                print("pcnt = %d, tot = %d, idx = %d" % (pcnt, tot, idx))
                stop = True
                break
        idx = idx + 2
Ejemplo n.º 18
0
def pe35(limit=1000000):
    """
    >>> pe35()
    55
    """
    ps = set(sieve(limit))
    s = 0
    # circ = []
    for p in ps:
        pl = len(str(p))
        for i in range(1, pl):
            t = 10 ** i
            pp = (p % t) * 10 ** (pl - i) + p // t
            if pp not in ps:
                break
        else:
            s += 1
            # circ.append(p)
    return s
Ejemplo n.º 19
0
def proj():
    idx = 2
    x = 1
    mx = 100000
    s = sieve(mx)
    tot, pcnt = 1, 0
    stop = False
    while not stop:
        for k in range(4):
            x = x + idx
            tot = tot + 1
            if s.is_prime(x):
                pcnt = pcnt + 1
            p = float(pcnt) / float(tot)
            if p < 0.1:
                print("pcnt = %d, tot = %d, idx = %d" % (pcnt, tot, idx))
                stop = True
                break
        idx = idx + 2
Ejemplo n.º 20
0
def pe35(limit=1000000):
    """
    >>> pe35()
    55
    """
    ps = set(sieve(limit))
    s = 0
    # circ = []
    for p in ps:
        pl = len(str(p))
        for i in range(1, pl):
            t = 10**i
            pp = (p % t) * 10**(pl - i) + p // t
            if pp not in ps:
                break
        else:
            s += 1
            # circ.append(p)
    return s
Ejemplo n.º 21
0
def pe50(below=1000000):
    """
    >>> pe50()
    (997651, 542)
    """
    primes = sieve(below)
    ps = set(primes)
    pl = len(primes)
    m, ml = 0, 0
    for j in range(pl - 500):
        t, s, l = 0, 0, 0
        for i in range(j, pl):
            s += primes[i]
            if s >= below:
                break
            if s in ps:
                t, l = s, i - j
        if l > ml:
            m, ml = t, l
    return (m, ml)
Ejemplo n.º 22
0
def pe50(below=1000000):
    """
    >>> pe50()
    (997651, 542)
    """
    primes = sieve(below)
    ps = set(primes)
    pl = len(primes)
    m, ml = 0, 0
    for j in range(pl - 500):
        t, s, l = 0, 0, 0
        for i in range(j, pl):
            s += primes[i]
            if s >= below:
                break
            if s in ps:
                t, l = s, i - j
        if l > ml:
            m, ml = t, l
    return (m, ml)
Ejemplo n.º 23
0
def find_prime_seq(limit):
    # Find the sequence of primes 2 + 3 + ... that just fits within the limit
    primes = sieve(limit)
    total = 0
    for i, p in enumerate(primes):
        total += p
        if total >= limit:
            total -= p
            end = i # primes[0:end] is the candidate sequence
            break
    # Now incrementally shorten the sequence until the total is prime.
    # This is the longest sequence possible below limit.
    for remove_terms in xrange(0, len(primes)):
        # ds = delta from start (0), de = delta from end
        for ds in xrange(0, remove_terms+1):
            de = remove_terms - ds
            tmp = total
            tmp -= sum(primes[0:ds])
            tmp -= sum(primes[end-de:end])
            if is_prime(tmp):
                return primes[ds:end-de]
Ejemplo n.º 24
0
def find_prime_seq(limit):
    # Find the sequence of primes 2 + 3 + ... that just fits within the limit
    primes = sieve(limit)
    total = 0
    for i, p in enumerate(primes):
        total += p
        if total >= limit:
            total -= p
            end = i  # primes[0:end] is the candidate sequence
            break
    # Now incrementally shorten the sequence until the total is prime.
    # This is the longest sequence possible below limit.
    for remove_terms in xrange(0, len(primes)):
        # ds = delta from start (0), de = delta from end
        for ds in xrange(0, remove_terms + 1):
            de = remove_terms - ds
            tmp = total
            tmp -= sum(primes[0:ds])
            tmp -= sum(primes[end - de:end])
            if is_prime(tmp):
                return primes[ds:end - de]
Ejemplo n.º 25
0
def pe37():
    """
    >>> pe37()
    [23, 37, 53, 73, 313, 317, 373, 797, 3137, 3797, 739397]
    """
    s = 0
    p0 = sieve(1000000)
    p = set(p0)
    p0 = set(p0[5:])
    t = []
    tl = 0
    for i in p0:
        i1 = i2 = str(i)
        f = True
        i1 = i1[:-1]
        while i1:
            if int(i1) in p:
                i1 = i1[:-1]
            else:
                f = False
                break
        if not f:
            continue
        i2 = i2[1:]
        while i2:
            if int(i2) in p:
                i2 = i2[1:]
            else:
                f = False
                break
        if f:
            t.append(i)
            # s += i
            tl += 1
            if tl >= 11:
                break
    return t
Ejemplo n.º 26
0
def pe37():
    """
    >>> pe37()
    [23, 37, 53, 73, 313, 317, 373, 797, 3137, 3797, 739397]
    """
    s = 0
    p0 = sieve(1000000)
    p = set(p0)
    p0 = set(p0[5:])
    t = []
    tl = 0
    for i in p0:
        i1 = i2 = str(i)
        f = True
        i1 = i1[:-1]
        while i1:
            if int(i1) in p:
                i1 = i1[:-1]
            else:
                f = False
                break
        if not f:
            continue
        i2 = i2[1:]
        while i2:
            if int(i2) in p:
                i2 = i2[1:]
            else:
                f = False
                break
        if f:
            t.append(i)
            # s += i
            tl += 1
            if tl >= 11:
                break
    return t
Ejemplo n.º 27
0
def proj():
    sv = sieve(10000)
    nmn = 2
    nmx = 10**7
    mn = nmx

    found = False
    print("Starting")
    for n in range(nmn,nmx+1):
        sys.stdout.write("n = %d\r" % n)
        totn = sv.totient(n)
        if not my_euler.is_permutation(n,totn):
            continue
        ratio = float(n)/float(sv.totient(n))
        if ratio<mn:
            found = True
            mn = ratio
            minn = n
        
    print("")
    if found:
        print("%d results in ratio %f" % (minn,mn))
    else:
        print("Nothing found")
Ejemplo n.º 28
0
def proj():
    sv = sieve(10000)
    nmn = 2
    nmx = 10**7
    mn = nmx

    found = False
    print("Starting")
    for n in range(nmn, nmx + 1):
        sys.stdout.write("n = %d\r" % n)
        totn = sv.totient(n)
        if not my_euler.is_permutation(n, totn):
            continue
        ratio = float(n) / float(sv.totient(n))
        if ratio < mn:
            found = True
            mn = ratio
            minn = n

    print("")
    if found:
        print("%d results in ratio %f" % (minn, mn))
    else:
        print("Nothing found")
Ejemplo n.º 29
0
Archivo: 41.py Proyecto: tkmckenzie/pan
from primes import sieve


def no_reps(n):
    a = list(str(n))
    return len(a) == len(set(a))


def is_pandigital(n, d):
    if not no_reps(n):
        return False
    else:
        a = list(str(n))
        a = [int(c) for c in a]
        nums = set(range(1, d + 1))
        return len(nums.intersection(a)) == len(nums.union(a)) == d


asdf
max_n = int(1e7)
primes = sieve(max_n)

pandigital_primes = sorted(list(filter(lambda x: is_pandigital(x, 7), primes)))
Ejemplo n.º 30
0
Archivo: 49.py Proyecto: tkmckenzie/pan
    return sorted(a1) == sorted(a2)
def find_arithmetic(a, length = 3):
    #Finds arithmetic sequence for given length, if one exists
    #Length must be greater than 2 (arithmetic sequence of length 2 is trivial)
    if length <= 2: raise ValueError('length must be greater than 2.')
    
    sequences = []
    a = sorted(a)
    
    for i in range(len(a)):
        n1 = a[i]
        for n2 in a[i+1:]:
            diff = n2 - n1
            if all([n1 + diff * k in a for k in range(2, length)]):
                sequences.append([n1, n2] + [n1 + diff * k for k in range(2, length)])
    
    return sequences
        

primes = sieve(9999)
primes = list(filter(lambda n: n >= 1000, primes))

results = []

for prime in primes:
    prime_permutations = list(filter(lambda n: is_permutation(prime, n), primes))
    arithmetic_sequences = find_arithmetic(prime_permutations, 3)
    results.extend(arithmetic_sequences)

print(set([''.join([str(n) for n in sorted(a)]) for a in results]))
Ejemplo n.º 31
0
# 15 = 3 × 5
#
# The first three consecutive numbers to have three distinct prime factors are:
#
# 644 = 2² × 7 × 23
# 645 = 3 × 5 × 43
# 646 = 2 × 17 × 19.
#
# Find the first four consecutive integers to have four distinct prime factors.
# What is the first of these numbers?


import primes
import sys

primes.sieve(140000)
target = 4

counter = 0
for x in range(2, 200000):
    # print(x, primes.factors(x))
    if (len(primes.factors(x)) >= target+1):
        counter += 1
    else:
        if (counter > 1):
            sys.stdout.write(str(counter))
            sys.stdout.flush()
        counter = 0
    if (counter == target):
        print('\n')
        print(x-target+1)
Ejemplo n.º 32
0
def get_permutations(x):
    "Return a list of all permutations of digits of x (as integers)."
    digits = get_digits(x)
    if len(digits) == 1:
        return digits
    result = []
    for i in range(0, len(digits)):
        combine = lambda d, e: int("".join(map(str, d)) + "".join(map(str, e)))
        result += map(lambda x: x*10 + digits[i],
                get_permutations(combine(digits[:i], digits[i+1:])))
    return list(set(result)) # Hacky duplicate filter

if __name__ == '__main__':
    # Ugly
    limit = 10000
    primes = sieve(limit)
    for p in primes:
        choices = filter(is_prime, get_permutations(p))
        choices = filter(lambda x: x > p, choices)
        for x in sorted(choices):
            step = x - p
            seq = [p, x]
            while True:
                x += step
                if x in choices:
                    seq.append(x)
                else:
                    break
            if len(seq) > 2:
                print 'Found:', seq
Ejemplo n.º 33
0
from primes import sieve, is_sieve_prime

s = sieve(8000000)


def max_factors(end):
    p = 1
    f = 0

    m = 2
    while m < end:
        p *= m
        m *= m
        f += 1
    for n in xrange(3, end, 2):
        if is_sieve_prime(s, n):
            m = n
            while m < end:
                p *= m
                m *= m
                f += 1

    print p % 500500507


max_factors(7370050)
Ejemplo n.º 34
0
"""

# euler 050
"""
The prime 41, can be written as the sum of six consecutive primes:

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 primes import sieve
import numpy as np

consecutiveSumPrimes = {}
primes = np.array(sieve(10**6 // 2), dtype='uint64')
primeSet = set(sieve(10**6))
shift = 0
primeSums = primes
while len(primeSums) > 0:
    shift += 1
    primeSums = primeSums[1:] + primes[:-shift]
    sumPrimes = [x for x in primeSums if x in primeSet]
    if len(sumPrimes) > 0:
        print(sumPrimes)
        consecutiveSumPrimes[shift + 1] = sumPrimes
Ejemplo n.º 35
0
from primes import sieve

primes = sieve()
result = 0

for prime in primes:
    if prime > 2000000:
        break

    result += prime

print result, prime
Ejemplo n.º 36
0
import primes

sum = 0
p = primes.primes(primes.sieve(2000100))
i = 0
while p[i] < 2000000:
    sum += p[i]
    i += 1

print sum
Ejemplo n.º 37
0
import primes
import operator
import math
import itertools
import unittest
import collections


primes = primes.sieve(10 ** 7)
print 'primes done'


def _number_of_digits(n):
    return int(math.ceil(math.log(n + 1, 10)))


def _int_to_reversed_digits(n):
    '''
    Reversed digits are great because the index is also the power of ten
    for that digit, making some forms of computation much easier.

    >>> sum(digit * 10 ** power for (power, digit) in enumerate(_int_to_reversed_digits(1482)))
    1482
    '''
    while True:
        quotient, remainder = divmod(n, 10)
        yield remainder
        if quotient == 0:
            return
        n = quotient
Ejemplo n.º 38
0
def num_diagonal_primes(side_length):
    primes = np.array(sieve(square_range(side_length)))
    is_diagonal = is_lower_right(primes) | is_lower_left(
        primes) | is_upper_left(primes) | is_upper_right(primes)
    return sum(is_diagonal)
Ejemplo n.º 39
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Find the smallest prime which, by changing the same part of the number,
can form eight different primes.
"""

from primes import sieve

primes = sieve(1000000)
primeset = set(primes)

def is_prime(n):
    return n in primeset

def get_char_index(s, n):
    index = []
    char = str(n)
    for i in range(len(s)):
        if s[i] == char:
            index.append(i)
    return index

def change(sp, n, index):
    sp = list(sp)
    for i in index:
        sp[i] = str(n + 1)
    return ''.join(sp)

def count_change(sp, n):
    cnt = 1
Ejemplo n.º 40
0
#link: https://projecteuler.net/problem=10

# The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
# Find the sum of all the primes below two million.

import primes

sieve = primes.sieve(2000000)

total = 0
for x in sieve:
    total += x

print(total)
Ejemplo n.º 41
0
from math import sqrt
from utils import chrono
from primes import getPrimes, isPrime, sieve
from itertools import product

primes, isP = sieve(1000000)


def getK(n):
    sum_divisors = 0
    len_divisors = 0
    N = n

    for p in primes:
        if p > n**0.5 and n != 1:
            len_divisors += 1
            sum_divisors += n
            break

        while n % p == 0:
            n //= p
            sum_divisors += p
            len_divisors += 1
    return len_divisors + N - sum_divisors


@chrono
def loop(kBound):
    highest_K = 0
    tot = 0
Ejemplo n.º 42
0
import itertools, primes

P = set(x for x in primes.sieve(10000) if x >= 1000)


for i in P:
    if i == 1487: continue
    s = ''.join(sorted(str(i)))
    perms = [x for x in P if ''.join(sorted(str(x))) == s and x != i]
    if len(perms) == 0: continue
    for j in perms:
        if (2 * j - i) in perms:
            print(str(i) + str(j) + str(2 * j - i))
            break
    else: continue
    break
Ejemplo n.º 43
0
from primes import sieve
N = 10000
primes = list(sieve(N))

prime_partitions = {n: 0 for n in range(N + 1)}
prime_partitions[0] = 1

for p in primes:
    for n in range(p, N+1):
        prime_partitions[n] += prime_partitions[n - p]

print [n for n in prime_partitions if prime_partitions[n] > 5000][0]
Ejemplo n.º 44
0
"""

from collections import namedtuple
from primes import sieve
from itertools import combinations
from math import sqrt
elem = namedtuple('elem', ['n', 'φ', 'ratio', 'primeDivisors'])

# the fewer the prime divisors, the higher the ratio n/φ(n).
# since if p a prime it's totient is p-1, we can't have just one prime divisor
# so we try two.

# we think that two primes around sqrt(10**7) will give the best result
# but we give a little more breathing room

primes = sieve(int(10 * sqrt(10**7)))
totients = []
for a, b in combinations(primes, 2):
    n = a * b
    if n < 10**7:
        totient = (a - 1) * (b - 1)
        if sorted(str(totient)) == sorted(str(n)) and n < 10**7:
            totients.append(elem(n, totient, n / totient, (a, b)))
totients.sort(key=lambda x: x.ratio)

for x in range(5):
    print(totients[x])
""" first attempt ('brute force') is preserved below: it gave me the idea 
but ran too slow """
#from factor import FactorizationDict
#F = FactorizationDict(maxElem = 10**5, fillFactorTree=True)
Ejemplo n.º 45
0
It was proposed by Christian Goldbach that every odd composite number can be 
written as the sum of a prime and twice a square.

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

from primes import sieve

primes = set(sieve(10**5))

primeCompositeSums = {
    prime + (2 * (n**2))
    for n in range(10**3) for prime in primes
}

oddComposites = (x for x in range(2, 10**5) if x not in primes and x % 2)

for x in oddComposites:
    if x not in primeCompositeSums:
        print(x)
        break
Ejemplo n.º 46
0
# It was proposed by Christian Goldbach that every odd composite number can be
# written as the sum of a prime and twice a square.
#
# 9 = 7 + 2×12
# 15 = 7 + 2×22
# 21 = 3 + 2×32
# 25 = 7 + 2×32
# 27 = 19 + 2×22
# 33 = 31 + 2×12
#
# 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 primes

sieve = primes.sieve(10000)

sums = set()

for i in range(200):
    square = 2*i*i
    for prime in sieve:
        sums.add(prime + square)


for i in range(3, 10000, 2):
    if not i in sums:
        print(i)
Ejemplo n.º 47
0
    "Return a list of all permutations of digits of x (as integers)."
    digits = get_digits(x)
    if len(digits) == 1:
        return digits
    result = []
    for i in range(0, len(digits)):
        combine = lambda d, e: int("".join(map(str, d)) + "".join(map(str, e)))
        result += map(lambda x: x * 10 + digits[i],
                      get_permutations(combine(digits[:i], digits[i + 1:])))
    return list(set(result))  # Hacky duplicate filter


if __name__ == '__main__':
    # Ugly
    limit = 10000
    primes = sieve(limit)
    for p in primes:
        choices = filter(is_prime, get_permutations(p))
        choices = filter(lambda x: x > p, choices)
        for x in sorted(choices):
            step = x - p
            seq = [p, x]
            while True:
                x += step
                if x in choices:
                    seq.append(x)
                else:
                    break
            if len(seq) > 2:
                print 'Found:', seq
Ejemplo n.º 48
0
import primes, number

P = list(primes.sieve(10000))

def isprime(n):
    if n <= max(P):
        return n in P
    return primes.isprime(n)

def prime(skip2 = False): # generator
    global P
    n = 0
    for p in P:
        if p == 2 and skip2: continue
        yield p
        n = p
    while True:
        n += 2
        valid = True
        for p in P:
            if p * p > n:
                break
            if n % p == 0:
                valid = False
                break
        if not valid: continue
        yield n
        P.append(n)

def until(gen, pred):
    for i in gen:
Ejemplo n.º 49
0
def largest_prod_less_than(n):
    prod = 1
    for prime in sieve(int(sqrt(n))):
        prod *= prime
	if prod > n: return prod / prime
Ejemplo n.º 50
0
from primes import sieve, is_sieve_prime, is_prime

s = sieve(10000000)
ns = [0] * 5


def prime(n):
    return is_sieve_prime(s, n) if n < 10000000 else is_prime(n)


def check(i, sn):
    for j in xrange(0, i):
        if not prime(int(ns[j] + sn)) or not prime(int(sn + ns[j])):
            return False
    return True


def find(i):
    a = 3 if i == 0 else int(ns[i - 1]) + 2
    for n in xrange(a, 8500):
        if prime(n):
            sn = str(n)
            if check(i, sn):
                ns[i] = sn
                if i < 4:
                    find(i + 1)
                else:
                    t = reduce(lambda accu, v: accu + int(v), ns, 0)
                    print t
Ejemplo n.º 51
0
from primes import primecheck, sieve
import time

n = 1000000

print "Primechecking method"
start = time.clock()
for i in range(n + 1):
    if primecheck(i): print i
timeTotalc = time.clock() - start
print

print
print "Sieve method"
start = time.clock()
primelist = sieve(n)
for i in primelist:
    print i
timeTotals = time.clock() - start
print
print
print "Primecheck took %f seconds to run." % (timeTotalc)
print "Sieve took %f seconds to run." % (timeTotals)
print
Ejemplo n.º 52
0
#! /usr/bin/env python3.2

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

"""


import sys
import os
sys.path.append(os.path.abspath('../'))
from primes import sieve

if __name__ == "__main__":
	from timeit import Timer
	try:
		x = int(sys.argv[1])
	
	except:
		x = 2
	t = Timer("sieve("  + str(x) + ")", "from __main__ import sieve")
	print(sieve(x))
	print(t.timeit(number = 10))
	
Ejemplo n.º 53
0
def truncations(number):
    truncations = set()
    divisor = 10
    n = number % divisor
    while number > divisor:
        truncations.add(n)
        divisor = divisor * 10
        n = number % divisor
    n = number / 10
    while n > 0:
        truncations.add(n)
        n = n / 10
    return truncations

limit = 10 ** 6
primes = primes.sieve(limit)
truncatable_primes = set()
for i in xrange(11, limit):
    if primes[i]:
        truncs = truncations(i)
        is_truncatable = True
        while len(truncs) > 0:
            trunc = truncs.pop()
            if not primes[trunc]:
                is_truncatable = False
                break
        if is_truncatable:
            truncatable_primes.add(i)
print sum(truncatable_primes)
Ejemplo n.º 54
0
import primes

p = primes.primes(primes.sieve(120000))
print p[10000]
def main ():
    sieve_array = sieve(100)
    prime_numbers = logical_to_integer (sieve_array, sum (sieve_array))
    print (prime_numbers)
Ejemplo n.º 56
0
# prime fourth power is 28. In fact, there are exactly four numbers below fifty
# that can be expressed in such a way:
# 
#    28 = 2**2 + 2**3 + 2**4 
#    33 = 3**2 + 2**3 + 2**4 
#    49 = 5**2 + 2**3 + 2**4 
#    47 = 2**2 + 3**3 + 2**4
# 
# How many numbers below fifty million can be expressed as the sum of a prime
# square, prime cube, and prime fourth power?

# Make a list of all the primes up to sqrt(fifty_million)
from primes import sieve

fifty_million = 50 * 10**6
P = list(sieve( int( (fifty_million)**.5 ) ))

# Solve the problem, brute force and not at all clever or thoughtful
numbers = set()
for p_1 in P:
   for p_2 in P:
       n = p_1**2 + p_2**3
       if n >= fifty_million: 
           break
       for p_3 in P:
           m = n + p_3**4
	   if m >= fifty_million:
	       break
	   else:
	       numbers.add(m)
Ejemplo n.º 57
0
def close_primes(N, delta):
    '''Make a list of the primes close to the square root of N.'''
    from math import sqrt
    rt_N = int(sqrt(N))
    return [p for p in sieve(rt_N + delta + 1)
                if abs(rt_N - p) < delta]
Ejemplo n.º 58
0
 def init_primes(self):
     self.primes_list = primes.sieve(5000)
Ejemplo n.º 59
0
import primes

# find LCM of any nums
nums = list(range(1, 21))

res = 1

def divideout(n):
    global nums
    ret = False
    for i in range(len(nums)):
        if nums[i] % n == 0:
            nums[i] = nums[i] // n
            ret = True
    return ret

for p in primes.sieve(max(nums)):
    while divideout(p): res *= p

print(res)
Ejemplo n.º 60
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?


import primes

stop = 1000000

sieve = primes.sieve(stop)

pset = set(sieve)

max = 0
sums = [0]*len(sieve)
for counter in range(0, stop):
    for i, prime in enumerate(sieve[counter:]):
        sums[i] += prime
        if sums[i] >= stop:
            break
        if counter > max and sums[i] in pset:
            print(counter + 1, sums[i])
            counter = max