Exemplo n.º 1
0
def truncatable(n):
    if not is_prime(n):
        return False
    for x in xrange(1,len(str(n))):
        if not is_prime(int(str(n)[:x])) or not is_prime(int(str(n)[x:])):
            return False
    return True
Exemplo n.º 2
0
def num_of_divisor(n):
    d = dict()

    cur = 2
    while True:
        if util.is_prime(cur):
            d[cur] = 0

            while n % cur == 0:
                n /= cur
                d[cur] += 1

            n = int(n)

            if n == 1:
                break
            elif util.is_prime(n):
                d[n] = 1
                break

        if cur == 2:
            cur += 1
        else:
            cur += 2

    ans = 1
    for (_, v) in d.items():
        ans *= v + 1

    return ans
Exemplo n.º 3
0
def solve():
    for p in primes2(3340):
        if p < 1000:
            continue
        p1 = p + 3330
        p2 = p + 6660
        if not is_prime(p1) or not is_prime(p2):
            continue
        if sorted(str(p)) == sorted(str(p1)) == sorted(str(p2)):
            return str(p) + str(p1) + str(p2)
Exemplo n.º 4
0
def is_prime_pair(a, b):
  ab = int(str(a) + str(b))
  if not util.is_prime(ab):
    return False

  ba = int(str(b) + str(a))
  if not util.is_prime(ba):
    return False

  return True
Exemplo n.º 5
0
def is_removeable_prime(n):
    if not is_prime(n):
        return False
    sn = str(n)
    for i in range(1, len(sn)):
        if not is_prime(int(sn[i:])):
            return False
        if not is_prime(int(sn[:i])):
            return False
    return True
Exemplo n.º 6
0
def is_truncatable_prime(n):
    if str(n)[0] not in ['2', '3', '5', '7'
                         ] or str(n)[-1] not in ['2', '3', '5', '7']:
        return False
    if not is_prime(n):
        return False
    n = str(n)
    truncs = [int(n[i:]) for i in range(len(n))
              ] + [int(n[:i + 1]) for i in range(len(n))]
    return all([is_prime(k) for k in truncs])
Exemplo n.º 7
0
def findPairs(i, primes):
    '''
    @param i Index of primes
    '''
    pairs = set()
    # startTime = time.time() 
    for j in range(i, len(primes)):
        if is_prime(concatenate(primes[i], primes[j])) and is_prime(concatenate(primes[j], primes[i])):
            pairs.add(primes[j])    
    # print('calculate pair[{0}] takes {1} seconds'.format(primes[i], time.time()-startTime))
    return pairs
Exemplo n.º 8
0
def solve():
    p = 33
    while 1:
        p += 2
        if not is_prime(p):

            for i in range(1, p / 2 + 1):
                if is_prime(p - 2 * i * i):
                    break
            else:
                return p
Exemplo n.º 9
0
def is_circular_prime(n):
    if not is_prime(n):
        return False
    digits = list(str(n))
    checklist = ['0', '4', '6', '8']
    if any([d in checklist for d in digits]):
        return False
    cycles = generate_rotation(n)
    while True:
        try:
            if not is_prime(int(next(cycles))):
                return False
        except StopIteration:
            return True
Exemplo n.º 10
0
def are_all_rotations_prime(n):
  if n < 2:
    return False

  if not util.is_prime(n):
    return False

  s = str(n)
  for i in range(len(s)):
    s2 = s[i:] + s[:i]
    if not util.is_prime(int(s2)):
      return False

  print '!!', n
  return True
Exemplo n.º 11
0
def get_prime_factors(n):
    result = set()
    for i in range(2, int(math.sqrt(n)) + 1):
        if n % i == 0:
            if is_prime(i):
                result.add(i)

            upper_divisor = int(n / i)
            if is_prime(upper_divisor):
                result.add(upper_divisor)

    if is_prime(n):
        result.add(n)

    return list(result)
Exemplo n.º 12
0
def is_truncatable_prime(n):
    num, ds = digits(n)
    # remove digits from left to right
    for i in xrange(1, len(ds)):
        tmp_ds = ds[i:]
        tmp_n = int(reduce(lambda x, y: ''.join([str(x), str(y)]), tmp_ds, ''))
        if not is_prime(tmp_n):
            return False
    # remove digits from right to left
    for i in xrange(1, len(ds)):
        tmp_ds = ds[:len(ds)-i]
        tmp_n = int(reduce(lambda x, y: ''.join([str(x), str(y)]), tmp_ds, ''))
        if not is_prime(tmp_n):
            return False
    return True
Exemplo n.º 13
0
def count_prime(a, b):
    n = 0
    while 1:
        if is_prime(abs(n * n + a * n + b)):
            n += 1
        else:
            return n
Exemplo n.º 14
0
def main():
    ans = 0
    for i in permutations("123456"):
        temp = int(num+"".join(i))
        if is_prime(temp) and temp > ans :
            ans = temp
    print ans
Exemplo n.º 15
0
def solution():
    count = 1
    n = 3
    while count < 10001:
        if is_prime(n):
            count += 1
        n += 2

    return n - 2
Exemplo n.º 16
0
    def find_primes_ceiling(self, starting_prime, ceiling) -> list:
        out_list = []
        for current_candidate in range(starting_prime, ceiling, 2):
            if util.is_prime(current_candidate):
                out_list.append(current_candidate)

        print("search ceiling exceeded, primes found this run {0:,.0f}".format(
            len(out_list)))
        return out_list
Exemplo n.º 17
0
def solution():
    count = 1
    n = 3
    while count < 10001:
        if is_prime(n):
            count += 1
        n += 2

    return n - 2
Exemplo n.º 18
0
def consecutive_primes(a, b):
    """
    Find the number of consecutive primes generated by the formula
    n² + an + b
    """
    n = 0
    while True:
        if not is_prime(n * n + a * n + b):
            return n
        n += 1
Exemplo n.º 19
0
def get_deepest_prime_below(sums, below):
  rr = []
  for y in reversed(xrange(len(sums))):
    for x in range(len(sums[y])):
      n = sums[y][x]
      if util.is_prime(n) and n < below:
        rr.append(n)
    if rr:
      break
  return rr
Exemplo n.º 20
0
def nth_prime(n):
    prime = 2
    count = 1
    k = 3
    while count < n:
        if is_prime(k):
            prime = k
            count += 1
        k += 2
    return prime
Exemplo n.º 21
0
def consecutive_primes(a, b):
    """
    Find the number of consecutive primes generated by the formula
    n² + an + b
    """
    n = 0
    while True:
        if not is_prime(n*n + a*n + b):
            return n
        n += 1
Exemplo n.º 22
0
def next(x):
    new_xs = []
    str_x = str(x)
    for (i,digit) in enumerate(str_x + '0'):
        for d in range(0,10):
            temp = str_x[:i] + str(d) + str_x[i:]
            if not (i == 0 and d == 0):
                if util.is_prime(int(temp)):
                    new_xs.append(int(temp))
    return new_xs
Exemplo n.º 23
0
def solution():
    target = 2e6
    i = 3
    total = 2
    while True:
        if is_prime(i):
            total += i
        i += 2
        if i > target:
            break
    return total
Exemplo n.º 24
0
def p131():
    # n**3 + p = (n+1)**3
    # p = 3n**2 + 3n + 1
    cnt = 0
    for n in count(1):
        p = 3 * (n**2) + 3 * n + 1
        if p >= 1000000:
            break
        if is_prime(p):
            cnt += 1
    print(cnt)
Exemplo n.º 25
0
def solution():
    count = 1
    i = 3
    target = 10001
    while(True):
        if is_prime(i):
            count += 1
        if count == target:
            break
        i += 2
    return i
Exemplo n.º 26
0
def pandigital_prime(n_digits):
    if n_digits % 2 == 0:
        start = int(str(n_digits) * n_digits) + 1
    else:
        start = int(str(n_digits) * n_digits)
    end = 10**(n_digits - 1)
    digits = set("".join(str(d) for d in xrange(1, n_digits + 1)))
    for i in xrange(start, end, -2):
        if set(str(i)) == digits:
            if util.is_prime(i):
                return i
Exemplo n.º 27
0
def main():
    i = 0
    n = 1

    while i < 10001:
        n += 1

        if is_prime(n):
            i += 1

    print(n)
Exemplo n.º 28
0
    def test_keygen(self):
        pk, sk = self.generate_keypair(_N_BITS)

        # check p and q are actually safe primes
        self.assertGreater(sk.p, 0)
        self.assertGreater(sk.q, 0)
        self.assertTrue(util.is_prime(sk.p))
        self.assertTrue(util.is_prime(sk.q))
        self.assertTrue(util.is_prime((sk.p - 1) // 2))
        self.assertTrue(util.is_prime((sk.q - 1) // 2))

        # check their sizes
        self.assertEqual(sk.p.bit_length() + sk.q.bit_length(), _N_BITS)
        self.assertGreaterEqual(sk.p.bit_length(), _N_BITS // 2)
        self.assertGreaterEqual(sk.q.bit_length(), _N_BITS // 2)

        # check consistency of n, nsquare and g
        self.assertEqual(pk.n, sk.p * sk.q)
        self.assertEqual(pk.nsquare, pk.n**2)
        self.assertGreater(pk.g, 0)
        self.assertLess(pk.g, pk.nsquare)
Exemplo n.º 29
0
Arquivo: 0037.py Projeto: Saiyan/euler
def is_truncatable_prime(string, left):
    n = int(string)
    if is_prime(n):
        if n < 10:
            return True
        else:
            next = string[0:-1]
            if left:
                next = string[1::]
            return is_truncatable_prime(next, left)
    else:
        return False
Exemplo n.º 30
0
def is_circular(n):
    if n in ps:
        return True
    s = str(n)
    ls = []
    for i in range(len(s)):
        if not is_prime(int(s)):
            return False
        ls.append(int(s))
        s = s[1:] + s[0]
    ps.extend(ls)
    return True
Exemplo n.º 31
0
def solve():
    """
    Generate permutations of range(1, n) and concatenate to form pandigital
    numbers. Start with n = 10 and count down until a prime pandigital is
    found.
    """
    for i in range(7, 1, -1):
        for p in itertools.permutations(range(i, 0, -1)):
            num = int("".join(str(i) for i in p))
            if (num % 2 != 0) and util.is_prime(num):
                print num
                return
Exemplo n.º 32
0
def main():
    prime_perc = 100
    total = 1
    num_prime = 0
    i = 1
    while prime_perc >= .10:
        i+=2
        total += 4
        for d in diagonal(i):
            num_prime += is_prime(d)
        prime_perc = float(num_prime)/total

    print i,prime_perc 
Exemplo n.º 33
0
def get_xth_prime(xth):
    primes_found = 0
    x = 2

    while True:

        if is_prime(x):
            primes_found += 1

            if primes_found == xth:
                return x

        x += 1
Exemplo n.º 34
0
def prime_proof(str_n):
    l = len(str_n)

    for i in range(l):
        ln = list(map(int, str_n))
        ln[i] = 0
        c = int(reduce(lambda x, y: str(x) + str(y), ln))
        # print(c, l - i - 1)
        for j in range(10):
            r = c + j * 10**(l - i - 1)
            if is_prime(r):
                return False
            # print('\t', r)
    return True
Exemplo n.º 35
0
def circular_primes(max_n):
    res = []
    for i in itertools.chain((2,), xrange(3, max_n + 1, 2)):
        s = str(i)
        l = len(s)
        if l > 1 and any([EVENS.search(s), "5" in s]):
            continue
        permutations = [int("".join(p)) for p in itertools.permutations(s, l)]
        for p in permutations:
            if not util.is_prime(p):
                break
        else:
            res.extend(permutations)
    return res
Exemplo n.º 36
0
Arquivo: 041.py Projeto: jag426/euler
def ppd():
    "pandigital primes descending"
    from itertools import permutations
    from math import floor
    from util import is_prime
    
    for n in range(0, 9):
        digits = '987654321'[n:]
        if sum(map(int, digits)) % 3 == 0:
            # every permutation will be divisible by 3
            continue
        for p in permutations(digits):
            x = int(''.join(p))
            if is_prime(x):
                yield x
Exemplo n.º 37
0
    def __init__(self, n: IntType) -> None:
        super().__init__()

        self.n = int(n)
        assert n >= 1

        self._props[RingProperties.FINITE] = True
        self._props[RingProperties.FIELD] = is_prime(n)
        self._props[RingProperties.ORDERED] = False

        # Register coercions. Only one we've got is from ZZ.
        def ZZ_coercion(x: IntegerElt) -> ZModElt:
            return self(x.value)

        self._register_coercion(ZZ, ZZ_coercion)
Exemplo n.º 38
0
def p179():  # 60 min > run time  (bad..)
    L = 10**7
    cnt = 1  # 2, 3
    last_fc = 0
    for i in range(2, L):
        if is_prime(i):
            last_fc = 0
            continue
        fc = factor_cnt(i)
        if last_fc == fc:
            cnt += 1
            print([i], fc, last_fc)
        last_fc = fc

    print('[179]: ', cnt)
    return
Exemplo n.º 39
0
def main(ceiling):
    """Tests to see if next number in sequence 6i+-1 is prime"""
    primes = [2, 3]
    i = 1
    switch = True 
    while primes[-1] <= ceiling:
        if switch:
            n = 6*i - 1
            switch = False
        else:
            n = 6*i + 1
            switch = True
            i+=1
        if is_prime(n, primes):
            primes.append(n)
            #print primes[-1]
    return primes
Exemplo n.º 40
0
    def find_primes_timelimit(self, starting_prime, timelimit_seconds) -> list:
        start_time = dt.datetime.now()
        print(
            f"find primes timelimit start time: {start_time.strftime('%H:%m')}"
        )

        current_candidate = starting_prime + 2
        out_list = []
        while (dt.datetime.now() - start_time).seconds < timelimit_seconds:
            if util.is_prime(current_candidate):
                out_list.append(current_candidate)

            current_candidate += 2

        print("search time limit exceeded, primes found this run {0:,.0f}".
              format(len(out_list)))
        return out_list
Exemplo n.º 41
0
def number_of_sum(m, n, d):
    if n == 0:
        return 1
    elif m == 1:
        return 0
    elif m == 2 and (n % 2) != 0:
        return 0

    if (m, n) in d:
        return d[(m, n)]

    ans = 0
    ans += number_of_sum(2, n - 2, d)
    for i in range(3, min(m + 1, n + 1), 2):
        if util.is_prime(i):
            ans += number_of_sum(i, n - i, d)

    d[(m, n)] = ans
    return ans
Exemplo n.º 42
0
def solution():
	ratio = 1.0
	start = 1
	step = 2
	count = 1
	countPrime = 0
	side = 1
	while ratio > 0.1:
		diagonals = [start + i * step for i in xrange(1, 5)]
		# print(diagonals)
		for n in diagonals:
			if is_prime(n): countPrime += 1
		count += 4
		
		ratio = float(countPrime) / float(count)
		# print(countPrime, count, ratio)
		# print(start, step, side)
		start = diagonals[3]
		step += 2
		side += 1
	return (side - 1) * 2 + 1
Exemplo n.º 43
0
def main():
    # Note that the constant term of the quadratic must be prime, because
    # when n = 0 it equals the constant term.
    # Also note that when n equals the constant term, every term will be
    # divisible by n and our list of primes terminates.
    answer = 0
    max_primes = 0
    primes = set(x for x in range(1000) if is_prime(x))

    for b in primes:
        for a in range(1, 1000):
            for a, b in ((a, b), (a, -b), (-a, b), (-a, -b)):
                q = quadratic(a, b)

                n = 0
                while q(n) in primes:
                    n += 1

                if n > max_primes:
                    answer = a * b
                    max_primes = n

    print(answer)
Exemplo n.º 44
0
def run(a, b):
    n = 0
    while is_prime(n**2 + a*n + b):
        n += 1
    return n
Exemplo n.º 45
0
#!/usr/bin/env python3

import sys
sys.path.insert(0, '../../')
import util

if __name__ == '__main__':

    max_len = 0
    ans = 0
    for a in range(-999, 1000):
        for b in range(-1000, 1001):
            cur = 0
            while True:
                f = cur**2 + a * cur + b
                if util.is_prime(f):
                    cur += 1
                else:
                    if cur > max_len:
                        max_len = cur
                        ans = a * b
                    break

    print(ans)
Exemplo n.º 46
0
def prime_genr(n=1):
    while True:
        if ut.is_prime(n):
            yield n
        n += 1
Exemplo n.º 47
0
def prime_list(lb=1, ub=100):
    return [n for n in range(lb, ub) if ut.is_prime(n)]
Exemplo n.º 48
0
#!/usr/bin/env python3

import sys
import math
import itertools
sys.path.insert(0, '../../')
import util

if __name__ == '__main__':

    max_ans = 0

    for n in range(9, 0, -1):
        lex = [str(i) for i in range(1, n + 1)]
        for i in itertools.permutations(lex):
            num = int(''.join(i))
            if util.is_prime(num) and num > max_ans:
                max_ans = num

        if max_ans > 0:
            break

    print(max_ans)
Exemplo n.º 49
0
from util import is_prime

for x in xrange(1000, 9999+1):
    if is_prime(x):
        perms = x, int(str(x)[1:]+str(x)[:1]), int(str(x)[2:]+str(x)[:2])
        if x == 1487:
            print perms[2]-perms[1] == perms[1]-perms[0]
        raw_input()
        if perms[2]-perms[1] == perms[1]-perms[0]:
            print 'found it'
Exemplo n.º 50
0
import util

primeCounter=0
i=0

while(primeCounter<10001):
        i+=1
        if(util.is_prime(i)):
            primeCounter+=1    
    
print primeCounter
print i
Exemplo n.º 51
0
            ]

            return [
                each_prime,
            ] + filtered_primes

    return False


if __name__ == '__main__':
    # test cases
    # assert is_permutation(1487, 4817)
    # assert is_permutation(1487, 8147)

    # approaches
    # 1
    # list primes in 1000 to 9999, find permutations

    # 2
    # for each prime in sequence, check if any permutations also prime

    # approach 1
    primes = [n for n in range(999, 10000) if ut.is_prime(n)]
    for each_prime in primes:
        prime_permuts = [n for n in primes if is_permutation(each_prime, n)]
        same_abs = find_same_abs(prime_permuts)

        if same_abs and same_abs[0] != 4817:
            print(same_abs)
            # 296962999629
Exemplo n.º 52
0
#!/usr/bin/env python3

import sys
import math
sys.path.insert(0, '../../')
import util

if __name__ == '__main__':

    cur = 3
    primes = {2: True}
    while True:

        if not util.is_prime(cur):

            have_sum = False
            for i in range(int(math.sqrt(cur / 2)) + 1):
                if (cur - 2 * i**2) in primes:
                    have_sum = True

            if not have_sum:
                print(cur)
                break

        else:
            primes[cur] = True

        cur += 2
Exemplo n.º 53
0
    return int(s[-1] + s[:-1])


if __name__ == '__main__':

    limit = 1000000
    l = set()
    not_l = set()

    for i in range(limit):
        if i in l or i in not_l:
            continue
        if '0' in str(i):
            continue

        if util.is_prime(i):
            temp = set([i])
            cur = i
            valid = True
            for j in range(len(str(i)) - 1):
                cur = circular(cur)
                temp.add(cur)
                if not util.is_prime(cur):
                    valid = False

            if valid:
                l |= temp
            else:
                not_l |= temp

    print(len(l))
Exemplo n.º 54
0
#!/usr/bin/env python3

import sys

sys.path.insert(0, '../../')
import util

if __name__ == '__main__':

    count = 11
    l = set()

    cur = 11
    while count > 0:
        if util.is_prime(cur):
            leng = len(str(cur))

            valid = True
            cur_left = cur
            cur_right = cur
            for i in range(leng - 1):
                cur_left = int(str(cur_left)[1:])
                cur_right = int(str(cur_right)[:-1])

                if util.is_prime(cur_left) and util.is_prime(cur_right):
                    pass
                else:
                    valid = False
                    break

            if valid:
Exemplo n.º 55
0
def get_biggest_pandigital_prime():
  for biggest_digit in range(1, 10)[::-1]:
    for n in pandigitals(biggest_digit):
      if util.is_prime(n):
        return n
  return None
Exemplo n.º 56
0
def main():
    print(sum(n for n in range(2, 2000000) if is_prime(n)))
Exemplo n.º 57
0
Arquivo: 051.py Projeto: jag426/euler
from util import is_prime, primes

pg = primes()
while next(pg) <= 56003:
    pass
answer = None
for p in pg:
    s = str(p)
    for d in range(3):
        if str(d) in s:
            n = 1
            for e in range(d+1, 10):
                if is_prime(int(s.replace(str(d), str(e)))):
                    n += 1
            if n >= 8:
                answer = p
                break
    if answer:
        break
print(answer)
Exemplo n.º 58
0
  prime_pair_cache[key] = r
  return r

def is_prime_set(selected, prime_pair_cache):
  for i in range(len(selected)):
    a = selected[i]
    for j in range(i):
      b = selected[j]
      if not is_prime_pair_caching(a, b, prime_pair_cache):
        return False
  return True

print 'getting primes up to %d...' % PRIMES_UP_TO
primes = []
for i in range(2, PRIMES_UP_TO):
  if util.is_prime(i):
    primes.append(i)

print 'getting prime pairs... (%d primes)' % (len(primes),)
prime_pair_cache = {}
prime2with = collections.defaultdict(list)
count = 0
for pair in itertools.combinations(primes, 2):
  if count % 100000 == 0:
    print 'checked %d pairs...' % count
  count += 1
  if is_prime_set(pair, prime_pair_cache):
    a, b = pair
    prime2with[a].append(b)
    prime2with[b].append(a)
Exemplo n.º 59
0
            break

        if cur_div == 2:
            cur_div += 1
        else:
            cur_div += 2

    return count

if __name__ == '__main__':

    cur = 644

    count = 0
    while True:
        
        if util.is_prime(cur):
            count = 0

        else:
            if primes_num(cur) == 4:
                count += 1
            else:
                count = 0

            if count == 4:
                print(cur - 3)
                break

        cur += 1
Exemplo n.º 60
0
import util

if __name__ == "__main__":
    n = 10
    print(n, util.is_prime(n))