def truncatable(n): if not is_prime(n): return False s = str(n) slen = len(s) for i in range(slen): if not is_prime(int(s[i:])): return False if not is_prime(int(s[:slen - i])): return False return True
def concat_prime(tuple): if len(tuple) != 2: raise AssertionError("concat_prime requires a tuple with 2 numbers") else: if is_prime(int(str(tuple[0]) + str(tuple[1]))) and is_prime( int(str(tuple[1]) + str(tuple[0]))): return True return False
def prime_after(n): current = n + 1 is_prime = utils.is_prime(current) while (not is_prime): current += 1 is_prime = utils.is_prime(current) return current
def truncatable(p): s = str(p) l = len(s) for i in range(1, l): if not is_prime(int(s[i:])): return False if not is_prime(int(s[:i])): return False return True
def truncatable_prime(n): str_n = str(n) for i in range(len(str_n)): right = int(str_n[:i+1]) left = int(str_n[i:]) if not is_prime(right) or not is_prime(left): return False return True
def prime_pair(a,b): a_b = a * 10 ** int(log10(b)+1) + b if not is_prime(a_b): return False b_a = b * 10 ** int(log10(a)+1) + a if not is_prime(b_a): return False return True
def solve(): for i in range(35,10000,2): if is_prime(i): continue else: found_one = 0 for x in range(1,int(math.sqrt(i)+1)): if is_prime(i-2*(x**2)): found_one = 1 if not found_one: return i
def main(): candidate = 7 while True: candidate += 2 if is_prime(candidate): continue for i in range(1, math.ceil(math.sqrt(candidate / 2))): if is_prime(candidate - 2 * i**2): break else: print(candidate) break
def is_prime_truncatable(n): right = n while num_digits(right) > 0: if not is_prime(right): return False right = rtrunc(right) left = n while num_digits(left) > 0: if not is_prime(left): return False left = ltrunc(left) return True
def longest_quad(a_lim, b_lim): longest = (0, 0, 0) for a in range((a_lim * -1) + 1, a_lim): # b must be prime in the case that n = 0 for b in range(2, b_lim): if is_prime(b): n, count = 0, 0 while is_prime(quad(a, b, n)): count += 1 n += 1 if count > longest[2]: longest = (a, b, count) return longest
def sum_harshad_primes(n): s = sum(int(d) for d in str(n)) assert n % s == 0 res = 0 for i in range(10): m = n * 10 + i if m > limit: break s2 = s + i if is_prime(m) and is_prime(n // s) and is_harshad(n // 10): res += m if m % s2 == 0: res += sum_harshad_primes(m) return res
def prime_factors(x): res = [] if is_prime(x): print("prime", x) res.append(x) return res for i in range(2, x // 2): if x % i == 0 and is_prime(i): res.append(i) res += prime_factors(x // i) break return res
def count_sets(digits, prev_choice=0): if len(digits) == 0: return 1 if len(digits) == 1: digit = digits.pop() return int(digit > prev_choice and is_prime(digit)) total = 0 for choice in chain.from_iterable( permutations(digits, r) for r in range(1, len(digits) + 1)): choice_int = concatenate(choice) if choice_int > prev_choice and is_prime(choice_int): total += count_sets(digits - set(choice), choice_int) return total
def truncatable(num): num = str(num) temp_num = str(num) for i in range(0, len(num) - 1): temp_num = temp_num[1:] if not utils.is_prime(int(temp_num)): return False for i in range(0, len(num) - 1): num = num[:-1] if not utils.is_prime(int(num)): return False return True
def main(): target = 2000 total = 2 # 1, 2 are special cases for n in count(2): if is_prime(6 * n - 1): if is_prime(6 * n + 1) and is_prime(12 * n + 5): total += 1 if total == target: print(3 * n * (n - 1) + 2) break if is_prime(6 * n + 5) and is_prime(12 * n - 7): total += 1 if total == target: print(3 * n * (n + 1) + 1) break
def count_primes(fun): counter = 0 for n in count(): if is_prime(fun(n)): counter += 1 else: return counter
def generate_shadows(k, s, p, ms, check=True): ms.sort() r = len(ms) #check if values meet requirements if check: if s > len(ms): raise Exception("Threshold cannot exceed the number of shadows.") if not utils.is_prime(p): raise Exception("p is not prime") for m in ms: if not utils.is_rel_prime(m, ms): raise Exception("The moduli must be pairwise relatively prime.") M = 1 for i in range(0, s): M *= ms[i] largest = p for i in range(0, s-1): largest *= ms[r-1-i] if M <= largest: raise Exception("The product of the smallest s moduli must be greater than the product of the s-1 largest moduli times p.") #print "M = ", M t = randint(0, int(M/p)) k0 = k + t*p #print k0 shadows = [] for m in ms: shadows.append(k0 % m) return t, shadows
def generate_shadows(k, s, p, ms, check=True): ms.sort() r = len(ms) #check if values meet requirements if check: if s > len(ms): raise Exception("Threshold cannot exceed the number of shadows.") if not utils.is_prime(p): raise Exception("p is not prime") for m in ms: if not utils.is_rel_prime(m, ms): raise Exception( "The moduli must be pairwise relatively prime.") M = 1 for i in range(0, s): M *= ms[i] largest = p for i in range(0, s - 1): largest *= ms[r - 1 - i] if M <= largest: raise Exception( "The product of the smallest s moduli must be greater than the product of the s-1 largest moduli times p." ) #print "M = ", M t = randint(0, int(M / p)) k0 = k + t * p #print k0 shadows = [] for m in ms: shadows.append(k0 % m) return t, shadows
def run(): to_proc = [] for prime in primes(1000,10000): to_proc.append(prime) to_proc.sort() permutations = [] for i in to_proc[:]: if len(permutations) == 2: break for j in xrange(1, (10000-i)/2): second = str(i+j) if is_prime(i+j) and is_permutation(str(i), second): third = i+j+j if is_prime(third) and is_permutation(second, str(third)): permutations.append((i,i+j,i+j+j)) print permutations
def consecutive_primes(a, b): count = 0 n = 0 while is_prime(n**2 + a * n + b): count += 1 n += 1 return count
def prime_series_length(a, b): """Find the number of primes for consecutive n, starting with n=0, for quad(n, a, b).""" n = 0 while is_prime(quad(n, a, b)): n += 1 return n
def primes(n): for p in range(2, n): if p in known_primes: yield p elif is_prime(p): known_primes[p] = None yield p
def main(): D = 10 digits = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) total = 0 for d in digits: for n in range(D-1, 0, -1): if d == 0 and n == D-1: continue S = 0 for indexes in combinations(range(D), n): repeating = [d if i in indexes else None for i in range(D)] for others in product(digits[:d] + digits[d+1:], repeat=D-n): others = iter(others) num = [next(others) if x is None else x for x in repeating] if num[0] and num[-1] in {1, 3, 7, 9} and sum(num) % 3: x = reduce(lambda x, y: x*10 + y, num) if is_prime(x): S += x if S: total += S break return total
def pollard_po(n, func=lambda x: x**2 + 1): x = random.randint(1, n - 2) y = 1 i = 1 stage = 2 while utils.gcd(n, x - y) == 1: if i == stage: y = x stage *= 2 x = func(x) % n i += 1 d = utils.gcd(n, x - y) b = n // d res = [d] if not utils.is_prime(b): b1, b2 = pollard_po(b) res.append(b1) if isinstance(b2, tuple): res.append(b2[0]) res.append(b2[1]) else: res.append(b2) return res res.append(b) return res
def isStrongRightTruncatableHarshadPrime(n): if not is_prime(n): return False else: s = str(n) t = int(s[:len(s)-1]) return isStrongHarshad(t)
def main(): # A prime n > 10 must end in one of these numbers. possible_prime_suffix = frozenset(('1', '3', '7', '9')) highest_prime = 0 # Progressivly create a smaller string of candidate numbers by # slicing the base str. str_num_base = '123456789' for x in range(9, 0, -1): str_num = str_num_base[:x] # Skip suffixes that are greater than the slice index, This stops # use getting possible values like 1239 which clearly isnt pandigital for suf in possible_prime_suffix: if int(suf) > x: continue # Remove the suffix from the number. suffed_str_num = str_num.replace(suf, '') # Get permutations of the remaining digits. # Append the suffix and check if the result is prime. for perm in permutations(suffed_str_num, x-1): i = int(''.join(perm) + suf) if is_prime(i): # Store the prime but continue for the same iteration of x # since its possible that smaller prime was given back from # permutations first. if i > highest_prime: highest_prime = i if highest_prime != 0: return highest_prime
def main(): for prime in prime_sieve_lazy(): if prime < 10**4: # rewind to the first 5-digit prime continue s = str(prime) # we're searching from low to high for digit in "012": count = s.count(digit) # Some observaions: # * count has to be a multiple of 3, otherwise some of the new # primes will be divisible by 3. # * the rightmost digit can't be replaced (it could only be "1") if count and not count % 3 and not digit == "1" == s[-1]: cnt = 1 for i in range(int(digit) + 1, 10): if i - cnt > 2: break if is_prime(int(s.replace(digit, str(i), count))): cnt += 1 if cnt == 8: return prime
def filter_real_part_not_prime(list_track): list_snapshot = track.peek(list_track) list_snapshot = [ item for item in list_snapshot if not utils.is_prime(item.real) ] track.push(list_track, list_snapshot)
def is_prime_cached(n): try: return prime_cache[n] except KeyError: p = is_prime(n) prime_cache[n] = p return p
def num_divisors(num): primes = utils.sieve_of_eratosthenes(int(math.ceil(math.sqrt(num)))) factors = [] prime_counter = 0 while num != 1: if prime_counter > len(primes) - 1: if num % 2 != 0 and num > 3 and utils.is_prime(num, 10): factors.append(num) break else: print("fail") break if num % primes[prime_counter] == 0: num /= primes[prime_counter] factors.append(primes[prime_counter]) else: prime_counter += 1 c = Counter(factors) product = 1 for key, value in c.iteritems(): value += 1 product *= value return product
def prime(n): if n not in prime_cache: if n > len(sieve): prime_cache[n] = is_prime(n) else: prime_cache[n] = sieve[n] return prime_cache[n]
def is_right_truncatable(p): p //= 10 while p > 0: if not is_prime(p): return False p //= 10 return True
def test_is_prime(self): self.assertTrue(is_prime(2)) self.assertTrue(is_prime(3)) self.assertTrue(is_prime(5)) self.assertTrue(is_prime(109)) self.assertTrue(is_prime(673)) self.assertFalse(is_prime(1)) self.assertFalse(is_prime(15)) self.assertFalse(is_prime(999))
def factorize(n, verbose=False, level=3): """ Factorizes a specified integer or returns -1 if no factors can be found. """ if verbose: if n != 1: print "Factoring", str(n) + "..." print "Number of digits:", len(str(n)) if n == 1: return [] if utils.is_prime(n): if verbose: print str(n), "is prime!" return [(n, 1)] else: f, f1 = [], [] if level > 2: # Try brute force for small prime factors if verbose: print "Finding small prime factors..." f, n = factorize_bf(n) if verbose: if not f: print "Found no small prime factors... :(" else: print "Prime factors found:", reduce( lambda x, y: x + y, [str(i[0]) + ", " for i in f])[:-2] if level > 1 and n <= constants.SIZE_THRESHOLD_RHO and n > 1: # Try Pollard rho if verbose: print_factoring_routine(n, constants.NAME_RHO) g = pollardRho.factorize_rho(n, verbose=verbose) if g != -1: if verbose: print "Found factor", str(g) f1 = merge_factorizations(factorize(g, verbose = verbose, level = 2), \ factorize(n/g, verbose = verbose, level = 2)) if f1 != -1: f.extend(f1) if level > 0 and (f1 == -1 or n > constants.SIZE_THRESHOLD_RHO) and n > 1: # If Pollard rho fails try ECM if verbose: print_factoring_routine(n, constants.NAME_ECM) g = ecm.factorize_ecm(n, verbose=verbose) if g != -1: if verbose: print "Found factor", str(g) f1 = merge_factorizations(factorize(g, verbose = verbose, level = 2), \ factorize(n/g, verbose = verbose, level = 2)) if f1 != -1: f.extend(f1) else: f = -1 return f
def num_consec_primes(a, b): primes = 0 n = 0 while utils.is_prime(n * n + n * a + b): primes += 1 n += 1 return n
def largest_prime_factor(number): max = int(math.floor(math.sqrt(number))) for n in xrange(max, 1, -1): if (number % n == 0 and utils.is_prime(n)): return n else: continue return number
def prime_at_position(position): current_prime = 2 primes_found = 1 while (primes_found < position): current_prime += 1 if (is_prime(current_prime)): primes_found += 1 return current_prime
def main(): most_successive_primes = 0 for a in range(-999, 1000): for b in range(2, 1001): if not is_prime(b): continue quad = lambda x: x * x + a * x + b n = 0 successive_primes = 0 while is_prime(quad(n)): successive_primes += 1 n += 1 if most_successive_primes < successive_primes: most_successive_primes = successive_primes best_a = a best_b = b print(best_a * best_b)
def run(): i = 1 count = 0 while count < 10091: i += 1 if utils.is_prime(i): count += 1 print i
def main(): start_permutation = [9, 8, 7, 6, 5, 4, 3, 2, 1] while len(start_permutation) > 1: for i in permutations(start_permutation): if utils.is_prime(to_int(i)): print to_int(i) return start_permutation = start_permutation[1:]
def is_circular(p): pow10 = 10**len(str(p)) tmp = (p * 10) // pow10 + (p * 10) % pow10 while tmp != p: if not is_prime(tmp): return False tmp = (tmp * 10) // pow10 + (tmp * 10) % pow10 return True
def prime_perms(): selected = [] for i in range(1000, 9999): if is_prime(i): allperms = sorted( list( set([ k for k in get_digit_permutations(i) if len(str(k)) == 4 and is_prime(k) ]))) if len(allperms) >= 3: for ecomb in list(combinations(allperms, 3)): if set(np.diff(ecomb)) == set([3330]): _s = "".join([str(k) for k in sorted(ecomb)]) if _s not in selected: selected.append(_s) print('Concatenated Numbers : ', selected)
def prime_by_index(number, index): prime_index = 0 for (idx, v) in enumerate(range(2, number)): if is_prime(v): prime_index += 1 print(v, prime_index) if index == prime_index: return v
def consecutive_primes(a, b): ''' Find the number of consecutive primes generated by an a, b pair in the expression n^2 + a*n + b ''' n = 0 while is_prime(n*n + a*n + b): n += 1 return n
def is_left_truncatable(p): pow10 = 10**(len(str(p)) - 1) p %= pow10 while p > 0: if not is_prime(p): return False pow10 //= 10 p %= pow10 return True
def gen_params(bits): while True: ptildprim = utils.randomnumber(pow(2, bits >> 1)) qtildprim = utils.randomnumber(pow(2, bits >> 1)) ptild = (2 * ptildprim + 1) qtild = (qtildprim + 1) if utils.is_prime(ptild) and utils.is_prime(qtild): break ntild = ptild * qtild pq = ptildprim * qtildprim while True: h2 = utils.randomnumber(ntild) if utils.nonrec_gcd(h2, ntild) == 1 and utils.powmod(h2, pq, ntild) == 1: break x = utils.randomnumber(pq) h1 = utils.powmod(h2, x, ntild) return ntild, h1, h2
def fns(a, b): """ yields n**2 + a*n + b for consec n=0, 1, 2, ... while prime """ func = lambda n: n**2 + a * n + b n = 0 while func(n)>1 and is_prime(func(n)): n += 1 yield func(n)
def main(): composites = [] for n in count(9, 2): # A(n) divides n-1 iff 10^(n-1)=1 (mod 9*n) if n % 5 and not is_prime(n) and pow(10, n - 1, 9 * n) == 1: composites.append(n) if len(composites) == 25: return sum(composites)
def main(): pandigital_numbers = [permutations(xrange(1, x)) for x in xrange(3, 9)] primes = [] for nums in pandigital_numbers: for n in nums: pn = int("".join(str(x) for x in n)) if is_prime(pn): primes.append(pn) print "The largest 1 to n pandigital prime is {prime}.".format(prime=max(primes))
def main(): composites = [] for n in count(9, 2): # A(n) divides n-1 iff 10^(n-1)=1 (mod 9*n) if n % 5 and not is_prime(n) and pow(10, n - 1, 9*n) == 1: composites.append(n) if len(composites) == 25: return sum(composites)
def primes_exp(num_a, num_b): '''Returns how many consecutive primes a quadratic expression with coefficients num_a and num_b returns''' count = 1 while is_prime(count ** 2 + num_a * count + num_b): count += 1 return count
def is_adv_prime(num): if not is_prime(num): return False primes.add(int(num)) for i in range(1, len(num)): if int(num[0:i]) not in primes: return False if int(num[-i:]) not in primes: return False return True
def check_perms(n): perms = [int(''.join(p)) for p in itertools.permutations(str(n), 4)] perms = [perm for perm in perms if utils.is_prime(perm) and perm >= 1000] for i in range(0, len(perms)): for j in range(i + 1, len(perms)): for h in range(j + 1, len(perms)): if (perms[i] != perms[j] != perms[h] and equal_gap(perms[i], perms[j], perms[h])): return (str(perms[i]) + ', ' + str(perms[j]) + ', ' + str(perms[h]))
def is_prime_family(masks, size): db = dict().fromkeys(masks, 0) for key,val in db.items(): for n in range(0, 10): if n == 0 and key[0] == "*": continue num = int(key.replace("*", str(n))) if is_prime(num): db[key] += 1 if db[key] == size: return True return False
def inner(digits): perms = permutations(digits) # filtering and sorting can make it even slower # print "filtering even" for idx, p in enumerate(perms): num = int(''.join(p)) if is_prime(num): print "after %d checks found %d" % (idx, num) return num return False