def isirreducible(n): if (n.real**2 == 1 and n.imag**2 == 1): return True elif (n.real % 4 == 3 and isprime(n.real) and n.imag == 0): return True elif(n*n.conjugate() % 4 == 1 and isprime(n*n.conjugate())): return True return False
def mySimulate(): a = 1 b = 0 c = 0 d = 0 e = 0 f = 0 g = 0 h = 0 b = 81 c = b if a != 0: b = 108100 c = b + 17000 else: b = 81 c = b while True: f = 1 if not isprime(b): h += 1 if c == b: return h b += 17
def find_prime_power(N): for i in range(2, int(math.log(N, 2) + 1)): [flag, b] = find_largest_b(N, i) if flag == 1: if isprime(b): return [b, i] return str(N) + " is not a prime power"
def test_prps(): oddcomposites = [n for n in range(1, 10**5) if n % 2 and not isprime(n)] # A checksum would be better. assert sum(oddcomposites) == 2045603465 assert [n for n in oddcomposites if mr(n, [2])] == [ 2047, 3277, 4033, 4681, 8321, 15841, 29341, 42799, 49141, 52633, 65281, 74665, 80581, 85489, 88357, 90751] assert [n for n in oddcomposites if mr(n, [3])] == [ 121, 703, 1891, 3281, 8401, 8911, 10585, 12403, 16531, 18721, 19345, 23521, 31621, 44287, 47197, 55969, 63139, 74593, 79003, 82513, 87913, 88573, 97567] assert [n for n in oddcomposites if mr(n, [325])] == [ 9, 25, 27, 49, 65, 81, 325, 341, 343, 697, 1141, 2059, 2149, 3097, 3537, 4033, 4681, 4941, 5833, 6517, 7987, 8911, 12403, 12913, 15043, 16021, 20017, 22261, 23221, 24649, 24929, 31841, 35371, 38503, 43213, 44173, 47197, 50041, 55909, 56033, 58969, 59089, 61337, 65441, 68823, 72641, 76793, 78409, 85879] assert not any(mr(n, [9345883071009581737]) for n in oddcomposites) assert [n for n in oddcomposites if is_lucas_prp(n)] == [ 323, 377, 1159, 1829, 3827, 5459, 5777, 9071, 9179, 10877, 11419, 11663, 13919, 14839, 16109, 16211, 18407, 18971, 19043, 22499, 23407, 24569, 25199, 25877, 26069, 27323, 32759, 34943, 35207, 39059, 39203, 39689, 40309, 44099, 46979, 47879, 50183, 51983, 53663, 56279, 58519, 60377, 63881, 69509, 72389, 73919, 75077, 77219, 79547, 79799, 82983, 84419, 86063, 90287, 94667, 97019, 97439] assert [n for n in oddcomposites if is_strong_lucas_prp(n)] == [ 5459, 5777, 10877, 16109, 18971, 22499, 24569, 25199, 40309, 58519, 75077, 97439] assert [n for n in oddcomposites if is_extra_strong_lucas_prp(n) ] == [ 989, 3239, 5777, 10877, 27971, 29681, 30739, 31631, 39059, 72389, 73919, 75077]
def prime_list(): """Create prime number list below 1000000""" L = [] for n in range(1, 1000000): if isprime(n): L.append(n) return L
def shor(N): if isprime(N): print('{} is a prime'.format(N)) return -1 if N % 2 == 0: print('{}: N is even'.format(N)) return 2 for i in range(3, int(np.log2(N))): j = i while (j <= N): if j == N: print(str(N) + ': trivially, N={}^a for some int a'.format(i)) return i j *= i while (1): x = random.randint(2, int(np.sqrt(N))) if (np.gcd(x, N) != 1): print('{}: by randoming, got factor {}'.format(N, np.gcd(x, N))) return (np.gcd(x, N)) #print('Attempting: N={}, x={}'.format(N,x)) r = quantum_find_r_sped(x, N) #print('found r={}'.format(r)) if (r % 2 == 1): continue #print('(N,x,r)=({},{},{})'.format(N,x,r)) a = np.gcd((x**(int(r / 2)) - 1) % N, N) #print('a={}, ie {}'.format(a, int(a))) if (a == 1 or a == N): continue print('{}: Found (N,x,r)={},{},{} with factor {}'.format( N, N, x, r, np.gcd(int(a), N))) return np.gcd(int(a), N)
def __init__(self, p, g, y, name="Verifier"): """ Initializes the verifier. Checks the validity of the arguments, and sets the public parameters p, g, y. This method has to initialize instance variables p, g and y (c and b will remain unset until choose_b method is called). :param p: integer, modulus :param g: integer, base :param y: integer, g^x mod p :param name: optional string, name of the verifier (to be used when printing data to the console) """ self.p = None self.g = None self.y = None self.c = None self.b = None self.name = name try: assert (isprime(p)) assert (y < p) assert (is_primitive_root(g, p)) except: raise InvalidParams self.p = p self.g = g self.y = y print_debug("{}:\t\tInitialized with p = {}, g = {} and y = {}".format( self.name, self.p, self.g, self.y), LOG_INFO)
def LargestPrimeFactor(n="NAN"): if n == "NAN": n = int(input("LargestPrimeFactor(n), n = ")) num = str(n) rng = int(np.sqrt(n)) primes = np.array(primeslist(1, rng)) val = n while isprime(val) == False: vals = np.linspace(val, val, len(primes)) print(vals) divs = vals / primes print(divs) counter = 0 for i in range(len(primes)): if int(divs[i]) == divs[i]: print(divs[i], " for ", primes[i]) val = divs[i] print(val) if val == 1: LPF = primes[i] print("The largest prime factor of ", num, " is ", LPF) return LPF else: break else: counter += 1 if counter == len(primes): print("loop encountered") LPF = val print("The largest prime factor of ", num, " is ", LPF) return LPF
def is_prime_as_int(n0: Union[int, float, complex]) -> int: n = cint(n0) if n != n0: return 0 try: from sympy.ntheory.primetest import isprime except ModuleNotFoundError: raise Exception("Install sympy to use number-theoretic functions!") # Note: If it ever matters, nonpositive integers are not prime. return int(isprime(n))
def is_exatly_prime_64(num): """ Точная проверка того, простое ли (True) или составное (False) число, работает только в диапазоне [0, 2*64) """ if num >= 2**64: raise ValueError( "Эта функция работает только в диапазоне [0, 2*64)") return primetest.isprime(num)
def inv_fermat(self, a, n): if isprime(n): if a < 0: a = a % n b = a for i in range(n - 3): b = b * a % n return b else: return "n is not prime"
def generatesMaxSequence(self): ''' The length K of a multiplicative congruence generator satisfies the following properties: - If K = M-1, then M is prime - K divides M -1 - K = M - 1 if and only if a is a primitive root of M and M is prime ''' res = isprime(self.moduli) and isPrimitiveRoot(self.a, self.moduli) return res
def primegenerating(n): if is_square(n): return 0 for div in divisors( n ): #unfortunately a generator does not work, as it does not order the divisors, and we would break out of the loop too soon. if div * div > n: break if not isprime(div + (n // div)): return 0 return n
def quick(position): """Quick tests for whether the position status is known.""" # All enders/quiet-enders are N except {2, 3}. # Note that [1] is irreducible (p) according to our definitions if position.gcd == 1 and position.irreducible \ and position.generators != [2, 3]: return "N" # Single primes greater than 3 are P if len(position.generators) == 1 and position.generators[0] > 3 \ and isprime(position.generators[0]): return "P"
def N(a, b): primes = [] for n in range(max(abs(a), abs(b))): num = f(n, a, b) # print(num) if isprime(num): primes.append(num) else: break nprimes = len(primes) return (nprimes)
def solve1(printflag, allflag, b): sols = canned1.get(b) if sols: if printflag: for sol in sols: print("{}!".format(sol)) if not allflag: break return sols[0] if isprime(b): return 0 raise ValueError("Cannot solve {{{}}}".format(b))
def peel_right(i): """"Remove digits right to left, then check for prime number""" x = list(str(i)) for n in range(1, len(x)): y = x[:(-n)] s = int(''.join(y)) if isprime(s): continue else: return "False" return "True"
def generate_prime_number(length=1024): """ Generate a prime Args: length -- int -- length of the prime to generate, in bits return a prime """ p = 4 # keep generating while the primality test fail while not isprime(p): p = generate_prime_candidate(length) # print("prime generated: %d" %p) return p
def generate_primes(): p = None q = None while (p == None) or (q == None): odd_rand_num = random.randrange(100000, 999999) if isprime(odd_rand_num): if p == None: p = odd_rand_num else: q = odd_rand_num print("Your private key is: ", (p, q)) return (p, q)
def quadratic_primes(arange): a, b, max_n = [0, 0, 0] for i in prime_sieve(arange + 1): # b must be prime for j in range(-i + 2, 0, 2): n = 1 while isprime( n * n + j * n + i ): # equation= n^2 + a*n + b, it has to generate prime numbers n += 1 if n > max_n: a, b, max_n = j, i, n return a * b
def check_prime(self, n): """ Функция проверки простоты числа (используется класс Primes из библиотеки sage) Parameters ---------- n : Union[int, gmpy2.mpz] Число для проверки Returns ------- bool Простое ли число """ return isprime(int(n))
def naive_search(M, N, J): p = np.array([0] * N) p[0], p[-1] = 1, 1 jamcoins = [] proofs = [] for i in range(0, 2**(N - 2)): p_ = [int(a) for a in str(bin(i))[2:]] p[-(len(p_) + 1):-1] = p_ c = [sum([a * b for a, b in zip(p, D)]) for D in M] if all([not isprime(a) for a in c]): jamcoins.append("".join([str(a) for a in p])) proofs.append([min(list(factorint(a).keys())) for a in c]) if len(jamcoins) == J: break return jamcoins, proofs
def __init__(self, p, n=1): p, n = int(p), int(n) if not isprime(p): raise ValueError("p must be a prime number, not %s" % p) if n <= 0: raise ValueError("n must be a positive integer, not %s" % n) self.p = p self.n = n if n == 1: self.reducing = [1, 0] else: for c in itertools.product(range(p), repeat=n): poly = (1, *c) if gf_irreducible_p(poly, p, ZZ): self.reducing = poly break
def add_primes(primes, switch): """Return the last number in the list (largest prime), and the in-loop counter (consecutive numbers)""" counter = switch # start with this prime number in_counter = 0 sum = 0 L = [] while sum < 1000000: sum = sum + primes[counter] if isprime(sum): L.append(sum) in_counter += 1 # in loop counter counter += 1 if L[-1] < 1000000: return L[-1], in_counter elif L[-1] > 1000000: print("****") return L[-2], in_counter
def main_code(x): N, J = tuple(map(int, input().split())) current = 1 + (2**(N - 1)) print("Case #" + str(x + 1) + ":") for _ in range(J): prime = True while prime: jamcoin = format(current, 'b') current += 2 prime = False proof = [] for base in range(2, 11): interpretation = int(jamcoin, base) if isprime(interpretation): prime = True break else: proof.append(str(primefactors(interpretation)[0])) print(jamcoin, " ".join(proof))
def compute_min_length(): cur_value = 1 num_primes = 0 for spiral_radius in itertools.count(1): gap_between_diagonals = 2 * spiral_radius # For each of the first three corners for _ in range(3): cur_value += gap_between_diagonals if isprime(cur_value): num_primes += 1 # Ignore the bottom right corner cur_value += gap_between_diagonals # There are 4 corners in each spiral, and one center number prime_ratio_of_diagonal = num_primes / (4 * spiral_radius + 1) if prime_ratio_of_diagonal < 0.1: return spiral_radius * 2 + 1
def number_replacement(combo, digit_dict, prime_set): prime_list = [] not_prime = 0 for digit in range(0,10): test_dict = dict(digit_dict) for pos in combo: test_dict[pos] = digit new_dig = int(''.join([str(x) for x in test_dict.values()])) #make sure the number hasn't been shortened by a leading zero if len(str(new_dig)) == len(digit_dict.keys()): if isprime(new_dig): prime_list.append(new_dig) else: not_prime += 1 if not_prime > (10 - prime_set): return [] return prime_list
def quadratic_primes(max_coefficient): '''Calculate the product of the coefficients that generate the most primes for a sequence of n starting with n=0 of the form: n^2 + an + b for |a| < max_coefficient and |b| < max_coefficient. ''' b_lst = list(sieve.primerange(1, max_coefficient)) max_n = 0 for a in range(-max_coefficient + 1, max_coefficient): for b in b_lst: n = 0 while isprime(n**2 + a * n + b): n += 1 if n > max_n: max_n = n max_product = a * b return max_product
def __init__(self, p, g, y, x, name="HonestProver"): """ Initializes the prover. Checks the validity of the arguments, sets the public parameters p, g, y and sets the secret x. This method has to initialize instance variables p, g, y and x (r will remain unset until compute_c method is called). :param p: integer, modulus :param g: integer, base :param y: integer, g^x mod p :param x: integer, secret :param name: optional string, name of the prover (to be used when printing data to the console) """ self.p = None self.g = None self.y = None self.x = None self.r = None self.name = name try: assert (isprime(p)) assert (y < p) assert (is_primitive_root(g, p)) if x is not None: assert (pow(g, x, p) == y) except: raise InvalidParams self.p = p self.g = g self.y = y self.x = x print_debug("{}:\tInitialized with p = {}, g = {}, y = {} and x = {}".format( self.name, self.p, self.g, self.y, self.x), LOG_INFO)
def __init__(self, p, n=None): if n is None: L = primeFact(p) if len(set(L)) > 1: raise ValueError('order must be a prime power') p = L[0] n = len(L) p, n = int(p), int(n) if not isprime(p): raise ValueError("p must be a prime number, not %s" % p) if n <= 0: raise ValueError("n must be a positive integer, not %s" % n) self.p = p self.n = n if n == 1: self.reducing = [1, 0] else: for c in itertools.product(range(p), repeat=n): poly = (1, *c) if gf_irreducible_p(poly, p, ZZ): self.reducing = poly break self.iterpos = 0
def solve_congruence(*remainder_modulus_pairs, **hint): """Compute the integer ``n`` that has the residual ``ai`` when it is divided by ``mi`` where the ``ai`` and ``mi`` are given as pairs to this function: ((a1, m1), (a2, m2), ...). If there is no solution, return None. Otherwise return ``n`` and its modulus. The ``mi`` values need not be co-prime. If it is known that the moduli are not co-prime then the hint ``check`` can be set to False (default=True) and the check for a quicker solution via crt() (valid when the moduli are co-prime) will be skipped. If the hint ``symmetric`` is True (default is False), the value of ``n`` will be within 1/2 of the modulus, possibly negative. Examples ======== >>> from sympy.ntheory.modular import solve_congruence What number is 2 mod 3, 3 mod 5 and 2 mod 7? >>> solve_congruence((2, 3), (3, 5), (2, 7)) (23, 105) >>> [23 % m for m in [3, 5, 7]] [2, 3, 2] If you prefer to work with all remainder in one list and all moduli in another, send the arguments like this: >>> solve_congruence(*zip((2, 3, 2), (3, 5, 7))) (23, 105) The moduli need not be co-prime; in this case there may or may not be a solution: >>> solve_congruence((2, 3), (4, 6)) is None True >>> solve_congruence((2, 3), (5, 6)) (5, 6) The symmetric flag will make the result be within 1/2 of the modulus: >>> solve_congruence((2, 3), (5, 6), symmetric=True) (-1, 6) See Also ======== crt : high level routine implementing the Chinese Remainder Theorem """ def combine(c1, c2): """Return the tuple (a, m) which satisfies the requirement that n = a + i*m satisfy n = a1 + j*m1 and n = a2 = k*m2. References ========== - http://en.wikipedia.org/wiki/Method_of_successive_substitution """ a1, m1 = c1 a2, m2 = c2 a, b, c = m1, a2 - a1, m2 g = reduce(igcd, [a, b, c]) a, b, c = [i//g for i in [a, b, c]] if a != 1: inv_a, _, g = igcdex(a, c) if g != 1: return None b *= inv_a a, m = a1 + m1*b, m1*c return a, m rm = remainder_modulus_pairs symmetric = hint.get('symmetric', False) if hint.get('check', True): rm = [(as_int(r), as_int(m)) for r, m in rm] # ignore redundant pairs but raise an error otherwise; also # make sure that a unique set of bases is sent to gf_crt if # they are all prime. # # The routine will work out less-trivial violations and # return None, e.g. for the pairs (1,3) and (14,42) there # is no answer because 14 mod 42 (having a gcd of 14) implies # (14/2) mod (42/2), (14/7) mod (42/7) and (14/14) mod (42/14) # which, being 0 mod 3, is inconsistent with 1 mod 3. But to # preprocess the input beyond checking of another pair with 42 # or 3 as the modulus (for this example) is not necessary. uniq = {} for r, m in rm: r %= m if m in uniq: if r != uniq[m]: return None continue uniq[m] = r rm = [(r, m) for m, r in uniq.iteritems()] del uniq # if the moduli are co-prime, the crt will be significantly faster; # checking all pairs for being co-prime gets to be slow but a prime # test is a good trade-off if all(isprime(m) for r, m in rm): r, m = zip(*rm) return crt(m, r, symmetric=symmetric, check=False) rv = (0, 1) for rmi in rm: rv = combine(rv, rmi) if rv is None: break n, m = rv n = n % m else: if symmetric: return symmetric_residue(n, m), m return n, m
def test_isprime(): s = Sieve() s.extend(100000) ps = set(s.primerange(2, 100001)) for n in range(100001): # if (n in ps) != isprime(n): print n assert (n in ps) == isprime(n) assert isprime(179424673) assert isprime(20678048681) assert isprime(1968188556461) assert isprime(2614941710599) assert isprime(65635624165761929287) assert isprime(1162566711635022452267983) assert isprime(77123077103005189615466924501) assert isprime(3991617775553178702574451996736229) assert isprime(273952953553395851092382714516720001799) assert isprime(int(''' 531137992816767098689588206552468627329593117727031923199444138200403\ 559860852242739162502265229285668889329486246501015346579337652707239\ 409519978766587351943831270835393219031728127''')) # Some Mersenne primes assert isprime(2**61 - 1) assert isprime(2**89 - 1) assert isprime(2**607 - 1) # (but not all Mersenne's are primes assert not isprime(2**601 - 1) # pseudoprimes #------------- # to some small bases assert not isprime(2152302898747) assert not isprime(3474749660383) assert not isprime(341550071728321) assert not isprime(3825123056546413051) # passes the base set [2, 3, 7, 61, 24251] assert not isprime(9188353522314541) # large examples assert not isprime(877777777777777777777777) # conjectured psi_12 given at http://mathworld.wolfram.com/StrongPseudoprime.html assert not isprime(318665857834031151167461) # conjectured psi_17 given at http://mathworld.wolfram.com/StrongPseudoprime.html assert not isprime(564132928021909221014087501701) # Arnault's 1993 number; a factor of it is # 400958216639499605418306452084546853005188166041132508774506\ # 204738003217070119624271622319159721973358216316508535816696\ # 9145233813917169287527980445796800452592031836601 assert not isprime(int(''' 803837457453639491257079614341942108138837688287558145837488917522297\ 427376533365218650233616396004545791504202360320876656996676098728404\ 396540823292873879185086916685732826776177102938969773947016708230428\ 687109997439976544144845341155872450633409279022275296229414984230688\ 1685404326457534018329786111298960644845216191652872597534901''')) # Arnault's 1995 number; can be factored as # p1*(313*(p1 - 1) + 1)*(353*(p1 - 1) + 1) where p1 is # 296744956686855105501541746429053327307719917998530433509950\ # 755312768387531717701995942385964281211880336647542183455624\ # 93168782883 assert not isprime(int(''' 288714823805077121267142959713039399197760945927972270092651602419743\ 230379915273311632898314463922594197780311092934965557841894944174093\ 380561511397999942154241693397290542371100275104208013496673175515285\ 922696291677532547504444585610194940420003990443211677661994962953925\ 045269871932907037356403227370127845389912612030924484149472897688540\ 6024976768122077071687938121709811322297802059565867''')) sieve.extend(3000) assert isprime(2819) assert not isprime(2931) assert not isprime(2.0)