def is_truncatable_prime(num: int) -> bool: """ Returns True is num is a truncatable prime. >>> is_truncatable_prime(3797) True >>> is_truncatable_prime(37) True >>> is_truncatable_prime(41) False >>> is_truncatable_prime(77) False >>> is_truncatable_prime(4) False >>> is_truncatable_prime(301997) False """ if not is_prime(num) or num <= 7: return False top_power = int(math.log10(num)) left = right = num for _ in itertools.repeat(None, top_power): left %= 10**top_power right //= 10 if not is_prime(left) or not is_prime(right): return False top_power -= 1 return True
def candidate_as(b, maxfound): """ Yields all possible values of `a` that would generate at least maxfound+1 consecutive primes """ for a in range(-MAX_MODULUS + 1, MAX_MODULUS): if common.is_prime(quadratic_value(maxfound, a, b)): if all(common.is_prime(quadratic_value(n, a, b)) for n in range(1, maxfound)): yield a
def get_ans(): maximum = 10000 - 3330 * 2 for i in xrange(1487 + 2, maximum, 2): if not is_prime(i): continue j = i + 3330 if not is_prime(j) or not is_perm(i, j): continue k = j + 3330 if not is_prime(k) or not is_perm(i, k): continue return '{0}{1}{2}'.format(i, j, k)
def is_circular_prime(num: int) -> bool: """ Returns True if all rotations of the decimal digits of `num` are prime. >>> is_circular_prime(197) True >>> is_circular_prime(31) True >>> is_circular_prime(23) False """ return is_prime(num) and all(is_prime(p) for p in numeric_rotations(num))
def is_circular_prime(x): # if initial number is not prime, bail out early if not is_prime(x): return False x = str(x) for i in range(1, len(x)): # right-half + left half final = x[i:] + x[0:i] if not is_prime(int(final)): return False return True
def Problem58(n: float): ''' For a number 0 < n < 1, returns the side length of the square for which the proportion of primes along the diagonals is less than n''' # Initialise the spiral with side length 3 start_time = time.time() diagonal = [1, 3, 5, 7, 9] side_length = 3 prime_count = 3 # Note that the ratio is not monotonically decreasing # However since the question asks for the first time it drops below n, this will do while (prime_count / len(diagonal) >= n): # Update the side length and step between each new number side_length += 2 step = side_length - 1 # At each new layer, we need to generate 4 new numbers # Add them to the diagonal, and to the prime counter if necessary for i in range(4): new_number = diagonal[-1] + step if (euler.is_prime(new_number)): prime_count += 1 diagonal.append(new_number) return side_length, '%.3f s' % (time.time() - start_time)
def check_equation(a, b): cnt = 0 for n in count(): if not is_prime(n * n + a * n + b): break cnt += 1 return cnt
def find_pattern(self, secret_length): """To find the pattern (so to find the indicator, the first channel & the second channel) we need to follow some rules based on the length of the secret : ╔════════════╦══════╦═══════╦═══════╗ ║ Parity bit ║ Even ║ Prime ║ Other ║ ╠════════════╬══════╬═══════╬═══════╣ ║ Even ║ RBG ║ BGR ║ GBR ║ ╠════════════╬══════╬═══════╬═══════╣ ║ Odd ║ RGB ║ BRG ║ GRB ║ ╚════════════╩══════╩═══════╩═══════╝ For example, if the length of the message is 17 : - 17 isnt even, but is a prime number --> Indicator == B - 17 in binary is 10001 so the parity is even --> first channel is G & second channel is R """ if secret_length % 2 == 0: pattern = "R" if parity_bit(secret_length): pattern += "BG" else: pattern += "GB" elif is_prime(secret_length): pattern = "B" if parity_bit(secret_length): pattern += "GR" else: pattern += "RG" else: pattern = "G" if parity_bit(secret_length): pattern += "BR" else: pattern += "RB" return pattern
def test_is_prime(self): self.assertTrue(is_prime(5)) self.assertTrue(is_prime(13)) self.assertTrue(is_prime(17)) self.assertTrue(is_prime(19)) self.assertTrue(is_prime(23)) self.assertFalse(is_prime(6)) self.assertFalse(is_prime(8)) self.assertFalse(is_prime(100))
def euler_3(): target = 600851475143 max_factor = 0 target_limit = int(round(sqrt(target))) for i in xrange(2, target_limit+1): if target % i == 0 and is_prime(i) and i > max_factor: max_factor = i return max_factor
def quad_prime_series(a, b): prime = {} n = 0 quad = b while(c.is_prime(quad)): prime[n] = quad n += 1 quad = (n * n) + (a * n) + b return(prime)
def num_of_primes(a, b): s = 0 for c in count(0): n = (c**2) + (a * c) + b if is_prime(n): s += 1 else: return s
def _solution(primes, begin, present, k): if len(present) == 0: present.append(primes[begin]) _solution(primes, begin + 1, present, k) if len(present) == k: return present for i in range(begin, len(primes)): flag = True for j in range(0, len(present)): if not is_prime(connect(primes[i], present[j])) or not is_prime(connect(present[j], primes[i])): flag = False break if flag: present.append(primes[i]) result = _solution(primes, i + 1, present, k) if result: return result present.pop()
def odd_composites(n=1000000): """ Find odd composites below n """ i = 3 while i < n: if not is_prime(i): yield i i += 2
def matches(n,diffs): for d in range(1,29,2): if is_prime(n+d): if d not in diffs: return False else: if d in diffs: return False return True
def solution(): TARGET = fractions.Fraction(1, 10) numprimes = 0 for n in itertools.count(1, 2): for i in range(4): if common.is_prime(n * n - i * (n - 1)): numprimes += 1 if n > 1 and fractions.Fraction(numprimes, n * 2 - 1) < TARGET: return str(n)
def matches(n, diffs): for d in range(1, 29, 2): if is_prime(n + d): if d not in diffs: return False else: if d in diffs: return False return True
def is_pass(n): i = 0 while True: twice_square = 2 * i * i if twice_square >= n: break if is_prime(n - twice_square): return True i += 1 return False
def num_prime_sum_ways(n): for i in range(primes[-1] + 1, n + 1): if common.is_prime(i): primes.append(i) ways = [1] + [0] * n for p in primes: for i in range(n + 1 - p): ways[i + p] += ways[i] return ways[n]
def _solution(primes, begin, present, k): if len(present) == 0: present.append(primes[begin]) _solution(primes, begin + 1, present, k) if len(present) == k: return present for i in range(begin, len(primes)): flag = True for j in range(0, len(present)): if not is_prime(connect(primes[i], present[j])) or not is_prime( connect(present[j], primes[i])): flag = False break if flag: present.append(primes[i]) result = _solution(primes, i + 1, present, k) if result: return result present.pop()
def euler_7(): prime_count = 0 PRIME_COUNT_TARGET = 10001 LIMIT = 9999999999999 # arbitrary for i in xrange(LIMIT): if is_prime(i): prime_count += 1 if prime_count == PRIME_COUNT_TARGET: return i
def factor(n): f = [] p_gen = prime_generator() while not is_prime(n) and n > 1: p = p_gen.next() while n % p == 0: n /= p f.append(p) print n if n != 1: f.append(int(n)) return f
def old_next_right_extend_prime(str_n): """Recursive return list of primes created by adding digits to the right. Stop if added digit creates non-prime.""" usable_digits = ('1', '3', '7', '9') # all possible multi-digit primes must end with one of these digits n = int(str_n) if common.is_prime(n): primes = [n] for p in usable_digits: primes.extend(old_next_right_extend_prime(str_n+p)) return primes else: return []
def largest_pandigital_prime(num): import sys sys.path.append('../') import common as c pand_list = c.permutation_numbers(str(num)) for item in pand_list: int_item = int(item) if ((int_item % 2) and (int_item % 5)): if (c.is_prime(int_item)): break print("max = ", int_item)
def factor_prime(x): if is_prime(x): return set([x]) res = set() for i in primes: if x == 1: return res while x % i == 0: res.add(i) x /= i res.add(x) return res
def old_next_left_extend_prime(str_n): """Recursive return list of primes created by adding digits to the left. Stop if added digit creates non-prime.""" usable_digits = ('1', '2', '3', '5', '7', '9') # will not generate complete list of primes - just those reducible to single digit primes. n = int(str_n) if common.is_prime(n): primes = [n] for p in usable_digits: primes.extend(old_next_left_extend_prime(p+str_n)) return primes else: return []
def solution(): limit = 10**9 result = set() for n in admissible(limit): # Pseudo-fortunate numbers must be odd for k in count(3, 2): if is_prime(n+k): result.add(k) break return sum(result)
def solve(): total = 1 primes = 0 for i in xrange(3, 100000, 2): for j in xrange(4): x = i * i - (i - 1) * j if is_prime(x): primes += 1 total += 1 if float(primes) / float(total) < 0.10: return i
def solution(): primes = 0 for idx, diagonal in enumerate(spiral_diagonals(), start=1): if is_prime(diagonal): primes += 1 if idx > 1 and primes*1.0/idx < 0.1: # idx-1 is the number of diagonals on non-zero length squares, # which is augmented by 3 before being divided by 4 (the number of # of diagonals per non-zero length square) to provide the "index" # of the outermost square. return ((idx-1) + 3)/4 * 2 + 1
def main(): hits = 0 total = 0 lim = 25 for n in count(7, 2): if n % 5 == 0 or is_prime(n): continue a = A(n) refresh("%d: %d", (n, a)) if (n - 1) % a == 0: print "%d: %d" % (n, a) total += n hits += 1 if hits >= lim: break print "Sum of first %d values is %d" % (lim, total)
def main(): MAX = 1000000 best = (0, 0) primes = list(sieve_primes(MAX)) sums = build_sums(primes) for first in range(0, len(sums)): last = len(sums) while last - first > best[1]: curr_sum = calc_curr_sum(first, last, sums) if is_prime(curr_sum): best = (curr_sum, last - first) break last -= 1 print(best)
def main(): hits = 0 total = 0 lim = 25 for n in count(7,2): if n % 5 == 0 or is_prime(n): continue a = A(n) refresh("%d: %d", (n,a)) if (n - 1) % a == 0: print "%d: %d" %(n,a) total += n hits += 1 if hits >= lim: break print "Sum of first %d values is %d" %(lim, total)
def solve(): x = 5 while True: if not is_prime(x): for p in gen_primes(x): a = x - p if a % 2 == 0: b = a / 2 b = sqrt(b) if b.is_integer(): break else: return x x += 2
def brute(lim): # 10, 315410, 927070 s = 0 for n in range(10, lim, 10): stdout.write("%d\r" % n) stdout.flush() for d in (1, 3, 7, 9, 13, 27): flag = True if not is_prime(n**2 + d): flag = False break if flag: s += n print "%3d: %3d" % (n, s) return s
def brute(lim): # 10, 315410, 927070 s = 0 for n in range(10,lim,10): stdout.write("%d\r" % n) stdout.flush() for d in (1,3,7,9,13,27): flag = True if not is_prime(n**2 + d): flag = False break if flag: s += n print "%3d: %3d" %(n, s) return s
def old_main(): nums = range(6) s = 10 for n in brute(150000000): stdout.write("%d\r" %(n)) stdout.flush() prime_flag = True for i,d in enumerate((1,3,7,9,13,27)): nums[i] = n**2 + d if not is_prime(nums[i]): prime_flag = False break if prime_flag: s += n print "%3d: [%6d, %6d, %6d, %6d, %6d, %6d]" % tuple([n] + nums) return s
def rec_primes(digit, num_digit, num_index, mark_digit, num_list, ans_list): if len(ans_list) == digit - 1: primes = [] start_mark_value = 0 if ans_list[0]!='*' else 1 for i in xrange(start_mark_value, 10, 1): val = int(''.join(ans_list + ['3']).replace('*', str(i))) if is_prime(val): primes += [val] yield primes return if num_digit + (mark_digit + 1) <= digit: for primes in rec_primes(digit, num_digit, num_index, mark_digit + 1, num_list, ans_list[:] + ['*']): yield primes if num_index < num_digit: for primes in rec_primes(digit, num_digit, num_index+1, mark_digit, num_list, ans_list[:] + [num_list[num_index]]): yield primes
def old_main(): nums = range(6) s = 10 for n in brute(150000000): stdout.write("%d\r" % (n)) stdout.flush() prime_flag = True for i, d in enumerate((1, 3, 7, 9, 13, 27)): nums[i] = n**2 + d if not is_prime(nums[i]): prime_flag = False break if prime_flag: s += n print "%3d: [%6d, %6d, %6d, %6d, %6d, %6d]" % tuple([n] + nums) return s
def spiral_primes(num=50001): import sys sys.path.append('../') import common as c # number of primes found, iteration number, corner values cnt, i, adder, corner, ok = 0, 0, 0, 1, True while (ok): i += 1 adder += 2 # keeps increasing by 2, 4, 6, 8, ... for j in range(4): corner += adder if (c.is_prime(corner)): cnt += 1 # keep tab of the primes prime_ratio = (cnt * 100) / (i * 4 + 1) if (prime_ratio < 10): # exit condition met? print("side = ", 2 * i + 1, "[[ ", i, cnt, i * 4 + 1, "{:10.7f}".format((cnt * 100) / (i * 4 + 1)), " ]]") ok = False
def solution(): base = 1000 # Keep the same iterator throughout to pull more prime values whenever # necessary iprimes = primes() # Use a set for quick prime lookups pset = set() for i in count(): limit = base*(10**i) pset.update(takewhile(lambda p: p < limit, iprimes)) tuples = set((p,) for p in pset) for j in range(2, 6): new_tuples = set() for ts in combinations(tuples, 2): t = tuple(sorted(set([e for t in ts for e in t]))) if len(t) != j: continue for a, b in permutations(t, 2): n = int(str(a) + str(b)) if n < limit: if n not in pset: break elif not is_prime(n): break else: new_tuples.add(t) tuples = new_tuples if tuples: return min((sum(t), t) for t in tuples)
def get_ans(): item = [1] item_size = 1 prime_count = 0 offset = 0 diff = 0 while True: diff += 2 for _ in xrange(4): next_item = item[offset] + diff if is_prime(next_item): prime_count += 1 item += [next_item] offset += 1 item_size += 4 if float(prime_count) / item_size < 0.1: return diff + 1
from common import is_prime from collections import Counter def IntToCounter(x): res = Counter() while x != 0: res[x % 10] += 1 x /= 10 return res primes = dict([(x, IntToCounter(x)) for x in xrange(1001, 10000) if is_prime(x)]) res = set() for a in primes.items(): for b in primes.items(): if a[0] == b[0] or a[1] != b[1]: continue aa = min(a[0], b[0]) bb = max(a[0], b[0]) cc = bb + (bb - aa) if cc in primes.keys() and primes[cc] == a[1]: res.add((aa, bb, cc)) for x in res: print x, str(x[0]) + str(x[1]) + str(x[2])
from itertools import count from common import is_prime, Watch Watch.start() found = False for n in count(100001, 2): number = str(n) for d in range(4): c = number.count(str(d), 0, -1) if c >= 3 and is_prime(n): occurrence = 1 for a in range(d + 1, 10): if 10 - a + occurrence < 8: break if is_prime(int(number.replace(str(d), str(a)))): occurrence += 1 if occurrence == 8: print(number) found = True break if found: break Watch.stop()
from common import is_prime target = 10001 n = 2 f = 0 while True: if is_prime(n): f += 1 if f == target: print n break n += 1
def euler_10(): sum_of_primes = 0 for i in xrange(2, LIMIT): if is_prime(i): sum_of_primes += i return sum_of_primes
def gen_primes(n): while n > 0: if common.is_prime(n): yield n n -= 1
__author__ = 'Andrey Smirnov' __email__ = '*****@*****.**' from common import is_prime, PRIMES for x in xrange(2, 1000): is_prime(x) primes = sorted(list(PRIMES)) def factor_prime(x): if is_prime(x): return set([x]) res = set() for i in primes: if x == 1: return res while x % i == 0: res.add(i) x /= i res.add(x) return res tmp = [] for x in xrange(2, 150000): lf = len(factor_prime(x)) tmp.append(lf) ltmp = len(tmp) if tmp[len(tmp)-4:] == [4, 4, 4, 4]: print x-3, len(factor_prime(x))
from collections import defaultdict import sys from common import is_prime, Watch, sieve_primes, d_count Watch.start() lim = 10000 primes, cat, graph = list(sieve_primes(lim)), lambda x, y: x * 10 ** d_count(y) + y, defaultdict(set) primes.remove(2) primes.remove(5) for i, p1 in enumerate(primes): for p2 in primes[i + 1:]: if is_prime(cat(p1, p2)) and is_prime(cat(p2, p1)): graph[p1].add(p2) max_sum = sys.maxsize for a in primes: xa = graph[a] for b in xa: xb = xa & graph[b] for c in xb: xc = xb & graph[c] for d in xc: xd = xc & graph[d] for e in xd: max_sum = min(max_sum, a + b + c + d + e) print(max_sum) Watch.stop()
from common import is_prime for p in range(10 ** 11 // 138, 10 ** 11 // 137): if p * 56789 % 10 ** 5 == 99999 and is_prime(p): print(9 * (p - 1) // 2)
from itertools import count from common import is_prime, Watch Watch.start() prime_count, total = 0, 1 for n in count(3, 2): square, total = n * n, total + 4 prime_count += sum(is_prime(square - i * (n - 1)) for i in range(1, 4)) if prime_count / total < 0.1: break print(n) Watch.stop()
# tail vs body print('tail test Fox x', is_correct_tail('Fox', 'x')) print('tail test Emu t', is_correct_tail('Emu', 't')) # min max in range print('min max test:') get_min_and_max() # testing integers print('what number test:') what_number() # get fact n = 5 print('n = {}, n! = {}'.format(n, factorial_loop(n))) # parse login print('login status:', make_login_procedure()) # test input integer print('negative integer test:') parse_integers() # test pack input integer print('pack integers test:') parse_pack_integers() # test prime print('prime test:') is_prime()
# It turns out that the formula will produce 40 primes for the consecutive values n = 0 to 39. However, when n = 40, 402 + 40 + 41 = 40(40 + 1) + 41 is divisible by 41, and certainly when n = 41, 41² + 41 + 41 is clearly divisible by 41. # Using computers, the incredible formula n² 79n + 1601 was discovered, which produces 80 primes for the consecutive values n = 0 to 79. The product of the coefficients, 79 and 1601, is 126479. # Considering quadratics of the form: # 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. from itertools import takewhile, count from common import is_prime def get_f(a, b): return lambda n: n * n + a * n + b maxa = maxb = max = 0 for a in range(-999, 1000): for b in range(-999, 1000): f = get_f(a, b) m = sum(1 for i in takewhile(lambda x: x > 0 and is_prime(x), (f(n) for n in count()))) if m > max: max = m maxa = a maxb = b print(max, maxa, maxb, maxa * maxb)
from common import is_prime if __name__ == "__main__": assert is_prime(221) == False assert is_prime(1478657) == False assert is_prime(1467733) == False n = 3 total = 1 count = 0 while True: total += 4 for x in [n**2 - n + 1, (n - 1)**2 + 1, (n - 1)**2 - (n - 1) + 1]: if is_prime(x): count += 1 if count / total < 0.1: print(n) exit() n += 2
from itertools import permutations from common import is_prime four_digit_primes = [] for i in xrange(10**3, 10**4): if is_prime(i): four_digit_primes.append(i) for i, a in enumerate(four_digit_primes): if a == 1487: # cited example continue for b in four_digit_primes[i+1:]: c = b + (b - a) if c in four_digit_primes: ta, tb, tc = [tuple(str(n)) for n in (a, b, c)] perms = list(permutations(ta)) if tb in perms and tc in perms: print str(a) + str(b) + str(c)
#coding:utf-8 ''' Created on 2016年1月3日 @author: robinjia @email: [email protected] ''' from common import is_prime if __name__ == "__main__": limit = 10001 count = 1 result = 2 while count < limit: result += 1 if is_prime(result): count += 1 print(result)
def solve(): cond = lambda i: (i % 5 != 0) and (not common.is_prime(i)) \ and ((i - 1) % leastDivisible(i) == 0) result = sum(itertools.islice(filter(cond, itertools.count(7, 2)), 25)) return str(result)