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) # Some Mersenne primes assert isprime(2**61 - 1) assert isprime(2**89 - 1) assert isprime(2**607 - 1) assert not isprime(2**601 - 1) #Arnault's number assert isprime(int(''' 803837457453639491257079614341942108138837688287558145837488917522297\ 427376533365218650233616396004545791504202360320876656996676098728404\ 396540823292873879185086916685732826776177102938969773947016708230428\ 687109997439976544144845341155872450633409279022275296229414984230688\ 1685404326457534018329786111298960644845216191652872597534901''')) # pseudoprime that passes the base set [2, 3, 7, 61, 24251] assert not isprime(9188353522314541) assert _mr_safe_helper( "if n < 170584961: return mr(n, [350, 3958281543])") == \ ' # [350, 3958281543] stot = 1 clear [2, 3, 5, 7, 29, 67, 679067]' assert _mr_safe_helper( "if n < 3474749660383: return mr(n, [2, 3, 5, 7, 11, 13])") == \ ' # [2, 3, 5, 7, 11, 13] stot = 7 clear == bases' assert isprime(5.0) is False
def _number(expr, assumptions): # helper method try: i = int(expr.round()) if not (expr - i).equals(0): raise TypeError except TypeError: return False return isprime(i)
def is_circ(n): s, i = str(n), 0 if '0' in s or '2' in s or '4' in s or '6' in s or '8' in s: return False while i < len(s): if not isprime(int(s)): return False s = s[1:len(s)]+s[0] i+=1 return True
def _number_theoretic_transform(seq, prime, inverse=False): """Utility function for the Number Theoretic Transform""" if not iterable(seq): raise TypeError("Expected a sequence of integer coefficients " "for Number Theoretic Transform") p = as_int(prime) if isprime(p) == False: raise ValueError("Expected prime modulus for " "Number Theoretic Transform") a = [as_int(x) % p for x in seq] n = len(a) if n < 1: return a b = n.bit_length() - 1 if n&(n - 1): b += 1 n = 2**b if (p - 1) % n: raise ValueError("Expected prime modulus of the form (m*2**k + 1)") a += [0]*(n - len(a)) for i in range(1, n): j = int(ibin(i, b, str=True)[::-1], 2) if i < j: a[i], a[j] = a[j], a[i] pr = primitive_root(p) rt = pow(pr, (p - 1) // n, p) if inverse: rt = pow(rt, p - 2, p) w = [1]*(n // 2) for i in range(1, n // 2): w[i] = w[i - 1]*rt % p h = 2 while h <= n: hf, ut = h // 2, n // h for i in range(0, n, h): for j in range(hf): u, v = a[i + j], a[i + j + hf]*w[ut * j] a[i + j], a[i + j + hf] = (u + v) % p, (u - v) % p h *= 2 if inverse: rv = pow(n, p - 2, p) a = [x*rv % p for x in a] return a
def test_randprime(): assert randprime(10, 1) is None assert randprime(2, 3) == 2 assert randprime(1, 3) == 2 assert randprime(3, 5) == 3 raises(ValueError, lambda: randprime(20, 22)) for a in [100, 300, 500, 250000]: for b in [100, 300, 500, 250000]: p = randprime(a, a + b) assert a <= p < (a + b) and isprime(p)
def rsa_private_key(p, q, e): r""" The RSA *private key* is the pair `(n,d)`, where `n` is a product of two primes and `d` is the inverse of `e` (mod `\phi(n)`). Examples ======== >>> from sympy.crypto.crypto import rsa_private_key >>> p, q, e = 3, 5, 7 >>> rsa_private_key(p, q, e) (15, 7) """ n = p*q phi = totient(n) if isprime(p) and isprime(q) and gcd(e, phi) == 1: return n, pow(e, phi - 1, phi) return False
def _number(expr, assumptions): # helper method exact = not expr.atoms(Float) try: i = int(expr.round()) if (expr - i).equals(0) is False: raise TypeError except TypeError: return False if exact: return isprime(i)
def test_randprime(): import random random.seed(1234) assert randprime(2, 3) == 2 assert randprime(1, 3) == 2 assert randprime(3, 5) == 3 raises(ValueError, lambda: randprime(20, 22)) for a in [100, 300, 500, 250000]: for b in [100, 300, 500, 250000]: p = randprime(a, a + b) assert a <= p < (a + b) and isprime(p)
def sumcons(Nmin, Nmax): retval = (-1, -1) tot = 0 for i, n in enumerate(nt.primerange(Nmin, Nmax)): if i == 0: continue if tot >= Nmax: break if nt.isprime(tot): retval = (i, tot) tot = tot + n return retval
def test_frt(): SIZE = 59 try: import sympy.ntheory as sn assert sn.isprime(SIZE) == True except ImportError: pass # Generate a test image L = np.tri(SIZE, dtype=np.int32) + np.tri(SIZE, dtype=np.int32)[::-1] f = frt2(L) fi = ifrt2(f) assert len(np.nonzero(L - fi)[0]) == 0
def rsa_public_key(p, q, e): r""" The RSA *public key* is the pair `(n,e)`, where `n` is a product of two primes and `e` is relatively prime (coprime) to the Euler totient `\phi(n)`. Examples ======== >>> from sympy.crypto.crypto import rsa_public_key >>> p, q, e = 3, 5, 7 >>> n, e = rsa_public_key(p, q, e) >>> n 15 >>> e 7 """ n = p*q phi = totient(n) if isprime(p) and isprime(q) and gcd(e, phi) == 1: return n, e return False
def isItJamCoin(number): binnumber = bin(number)[2:] divisors = [] for i in range(2, 11): current = int(binnumber, i) if isprime(current): return None divisor = min(factorint(current).keys()) if divisor == current: return None divisors.append(divisor) return divisors
def GetLongestConsSumPrimes(step,limit): sum = step count = 1 i = nextprime(step) while (sum + i)<limit: sum += i count += 1 i = nextprime(i) while isprime(sum) == False : i = prevprime(i) sum -= i count -= 1 return (count,sum)
def test_isprime(): s = Sieve() s.extend(100000) ps = set(s.primerange(2, 100001)) for n in range(100001): assert (n in ps) == isprime(n) assert isprime(179424673) # Some Mersenne primes assert isprime(2**61 - 1) assert isprime(2**89 - 1) assert isprime(2**607 - 1) assert not isprime(2**601 - 1)
def _check_cycles_alt_sym(perm): """ Checks for cycles of prime length p with n/2 < p < n-2. Here `n` is the degree of the permutation. This is a helper function for the function is_alt_sym from sympy.combinatorics.perm_groups. Examples ======== >>> from sympy.combinatorics.util import _check_cycles_alt_sym >>> from sympy.combinatorics.permutations import Permutation >>> a = Permutation([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [11, 12]]) >>> _check_cycles_alt_sym(a) False >>> b = Permutation([[0, 1, 2, 3, 4, 5, 6], [7, 8, 9, 10]]) >>> _check_cycles_alt_sym(b) True See Also ======== sympy.combinatorics.perm_groups.PermutationGroup.is_alt_sym """ n = perm.size af = perm.array_form current_len = 0 total_len = 0 used = set() for i in range(n // 2): if not i in used and i < n // 2 - total_len: current_len = 1 used.add(i) j = i while (af[j] != i): current_len += 1 j = af[j] used.add(j) total_len += current_len if current_len > n // 2 and current_len < n - 2 and isprime( current_len): return True return False
def _inv_totient_estimate(m): """ Find ``(L, U)`` such that ``L <= phi^-1(m) <= U``. Examples ======== >>> from sympy.polys.polyroots import _inv_totient_estimate >>> _inv_totient_estimate(192) (192, 840) >>> _inv_totient_estimate(400) (400, 1750) """ primes = [ d + 1 for d in divisors(m) if isprime(d + 1) ] a, b = 1, 1 for p in primes: a *= p b *= p - 1 L = m U = int(math.ceil(m*(float(a)/b))) P = p = 2 primes = [] while P <= U: p = nextprime(p) primes.append(p) P *= p P //= p b = 1 for p in primes[:-1]: b *= p - 1 U = int(math.ceil(m*(float(P)/b))) return L, U
def test_isprime(): s = Sieve() s.extend(100000) ps = set(s.primerange(2, 100001)) for n in range(100001): assert (n in ps) == isprime(n) assert isprime(179424673) # Some Mersenne primes assert isprime(2**61 - 1) assert isprime(2**89 - 1) assert isprime(2**607 - 1) assert not isprime(2**601 - 1) #Arnault's number assert isprime(int(''' 803837457453639491257079614341942108138837688287558145837488917522297\ 427376533365218650233616396004545791504202360320876656996676098728404\ 396540823292873879185086916685732826776177102938969773947016708230428\ 687109997439976544144845341155872450633409279022275296229414984230688\ 1685404326457534018329786111298960644845216191652872597534901''')) # pseudoprime that passes the base set [2, 3, 7, 61, 24251] assert not isprime(9188353522314541)
def Integer(expr, assumptions): return isprime(expr)
def is_prime(n): return isprime(n)
def _gen_prime(self, bits): """Generowanie liczby pierwszej o danej długości bitów""" k = 0 while not isprime(k): k = randint(2**(bits - 1), 2**bits) return k
def multiplicativeOrder(A, N): if (GCD(A, N) != 1): return -1 result = 1 K = 1 while (K < N): result = (result * A) % N if (result == 1): return K K = K + 1 return -1 d = 1 cycleLength = 1 for i in range(2, bound): if not nt.isprime(i): continue order = multiplicativeOrder(10, i) if order != -1 and order > cycleLength: cycleLength = order d = i print(d, cycleLength)
def dup_zz_zassenhaus(f, K): """Factor primitive square-free polynomials in `Z[x]`. """ n = dup_degree(f) if n == 1: return [f] fc = f[-1] A = dup_max_norm(f, K) b = dup_LC(f, K) B = int(abs(K.sqrt(K(n + 1)) * 2**n * A * b)) C = int((n + 1)**(2 * n) * A**(2 * n - 1)) gamma = int(_ceil(2 * _log(C, 2))) bound = int(2 * gamma * _log(gamma)) a = [] # choose a prime number `p` such that `f` be square free in Z_p # if there are many factors in Z_p, choose among a few different `p` # the one with fewer factors for px in range(3, bound + 1): if not isprime(px) or b % px == 0: continue px = K.convert(px) F = gf_from_int_poly(f, px) if not gf_sqf_p(F, px, K): continue fsqfx = gf_factor_sqf(F, px, K)[1] a.append((px, fsqfx)) if len(fsqfx) < 15 or len(a) > 4: break p, fsqf = min(a, key=lambda x: len(x[1])) l = int(_ceil(_log(2 * B + 1, p))) modular = [gf_to_int_poly(ff, p) for ff in fsqf] g = dup_zz_hensel_lift(p, f, modular, l, K) sorted_T = range(len(g)) T = set(sorted_T) factors, s = [], 1 pl = p**l while 2 * s <= len(T): for S in subsets(sorted_T, s): # lift the constant coefficient of the product `G` of the factors # in the subset `S`; if it is does not divide `fc`, `G` does # not divide the input polynomial if b == 1: q = 1 for i in S: q = q * g[i][-1] q = q % pl if not _test_pl(fc, q, pl): continue else: G = [b] for i in S: G = dup_mul(G, g[i], K) G = dup_trunc(G, pl, K) G = dup_primitive(G, K)[1] q = G[-1] if q and fc % q != 0: continue H = [b] S = set(S) T_S = T - S if b == 1: G = [b] for i in S: G = dup_mul(G, g[i], K) G = dup_trunc(G, pl, K) for i in T_S: H = dup_mul(H, g[i], K) H = dup_trunc(H, pl, K) G_norm = dup_l1_norm(G, K) H_norm = dup_l1_norm(H, K) if G_norm * H_norm <= B: T = T_S sorted_T = [i for i in sorted_T if i not in S] G = dup_primitive(G, K)[1] f = dup_primitive(H, K)[1] factors.append(G) b = dup_LC(f, K) break else: s += 1 return factors + [f]
def qs(N, prime_bound, M, ERROR_TERM=25, seed=1234): """Performs factorization using Self-Initializing Quadratic Sieve. In SIQS, let N be a number to be factored, and this N should not be a perfect power. If we find two integers such that ``X**2 = Y**2 modN`` and ``X != +-Y modN``, then `gcd(X + Y, N)` will reveal a proper factor of N. In order to find these integers X and Y we try to find relations of form t**2 = u modN where u is a product of small primes. If we have enough of these relations then we can form ``(t1*t2...ti)**2 = u1*u2...ui modN`` such that the right hand side is a square, thus we found a relation of ``X**2 = Y**2 modN``. Here, several optimizations are done like using muliple polynomials for sieving, fast changing between polynomials and using partial relations. The use of partial relations can speeds up the factoring by 2 times. Parameters ========== N : Number to be Factored prime_bound : upper bound for primes in the factor base M : Sieve Interval ERROR_TERM : Error term for checking smoothness threshold : Extra smooth relations for factorization seed : generate pseudo prime numbers Examples ======== >>> from sympy.ntheory import qs >>> qs(25645121643901801, 2000, 10000) {5394769, 4753701529} >>> qs(9804659461513846513, 2000, 10000) {4641991, 2112166839943} References ========== .. [1] https://pdfs.semanticscholar.org/5c52/8a975c1405bd35c65993abf5a4edb667c1db.pdf .. [2] https://www.rieselprime.de/ziki/Self-initializing_quadratic_sieve """ ERROR_TERM *= 2**10 rgen.seed(seed) idx_1000, idx_5000, factor_base = _generate_factor_base(prime_bound, N) smooth_relations = [] ith_poly = 0 partial_relations = {} proper_factor = set() threshold = 5 * len(factor_base) // 100 while True: if ith_poly == 0: ith_sieve_poly, B_array = _initialize_first_polynomial( N, M, factor_base, idx_1000, idx_5000) else: ith_sieve_poly = _initialize_ith_poly(N, factor_base, ith_poly, ith_sieve_poly, B_array) ith_poly += 1 if ith_poly >= 2**(len(B_array) - 1): # time to start with a new sieve polynomial ith_poly = 0 sieve_array = _gen_sieve_array(M, factor_base) s_rel, p_f = _trial_division_stage(N, M, factor_base, sieve_array, ith_sieve_poly, partial_relations, ERROR_TERM) smooth_relations += s_rel proper_factor |= p_f if len(smooth_relations) >= len(factor_base) + threshold: break matrix = _build_matrix(smooth_relations) dependent_row, mark, gauss_matrix = _gauss_mod_2(matrix) N_copy = N for index in range(len(dependent_row)): factor = _find_factor(dependent_row, mark, gauss_matrix, index, smooth_relations, N) if factor > 1 and factor < N: proper_factor.add(factor) while (N_copy % factor == 0): N_copy //= factor if isprime(N_copy): proper_factor.add(N_copy) break if (N_copy == 1): break return proper_factor
def test_dh_private_key(): p, g, _ = dh_private_key(digit = 100) assert isprime(p) assert is_primitive_root(g, p) assert len(bin(p)) >= 102
def _number(expr, assumptions): # helper method if (expr.as_real_imag()[1] == 0) and int(expr.evalf()) == expr: return isprime(expr.evalf(1)) return False
def is_truncprime(n): s = str(n) for i in xrange(1, len(s)): if not isprime(int(s[0:len(s)-i])): return False if not isprime(int(s[i:len(s)])): return False return True
# VERY SLOW 20 MINUTES from sympy.ntheory import isprime N = 50_000_000 cnt = 0 for n in range(2, N + 1): t = 2 * n * n - 1 if not isprime(t): continue cnt += 1 if cnt % 1000 == 0: print(n, t, cnt) print(cnt)
if checkWitness(a,n,r,fast) : return False return True; n=1; # while n>=1: # n =int(input()); # a=1; # r=int(input()); # print(polypow(a,n,r,100,True)); end=100 start_time = time.time() for i in range(1,end): withAks=aks(i); withSympy=isprime(i); if i%100==0 : print(i) if withAks!=withSympy: print('come on something is wrong slow') print("--- %s seconds ---" % (time.time() - start_time)) # start_time = time.time() # for i in range(37,end): # withAks=aks(i,True); # withSympy=isprime(i); # if i%100==0 : # print(i) # if withAks!=withSympy: # print('come on something is wrong Fast') # print("Fast--- %s seconds ---" % (time.time() - start_time))
for j in xrange(1, t + 1): print "Case #{}:".format(j) found = 0 for i in xrange(2**(N - 2), 2**(N - 1)): if found == J: break jamcoin = str(bin(i))[2:] + '1' non_trivial_divisors = [] for base in xrange(2, 11): jamcoin_base = int(jamcoin, base) if isprime(jamcoin_base): break else: div = pollard_pm1(jamcoin_base, retries=6) if div: non_trivial_divisors.append(div) if len(non_trivial_divisors) == 9: found += 1 divisors_str = "" for i in non_trivial_divisors: divisors_str += str(i) + " " print jamcoin, divisors_str[:-1]
from sympy.ntheory import isprime a = 1 b = c = d = e = f = g = h = 0 b = 108100 c = 125100 while True: if not isprime(b): h += 1 if b == c: break b += 17 print h
def _ecm_one_factor(n, B1=10000, B2=100000, max_curve=200): """Returns one factor of n using Lenstra's 2 Stage Elliptic curve Factorization with Suyama's Parameterization. Here Montgomery arithmetic is used for fast computation of addition and doubling of points in elliptic curve. This ECM method considers elliptic curves in Montgomery form (E : b*y**2*z = x**3 + a*x**2*z + x*z**2) and involves elliptic curve operations (mod N), where the elements in Z are reduced (mod N). Since N is not a prime, E over FF(N) is not really an elliptic curve but we can still do point additions and doubling as if FF(N) was a field. Stage 1 : The basic algorithm involves taking a random point (P) on an elliptic curve in FF(N). The compute k*P using Montgomery ladder algorithm. Let q be an unknown factor of N. Then the order of the curve E, |E(FF(q))|, might be a smooth number that divides k. Then we have k = l * |E(FF(q))| for some l. For any point belonging to the curve E, |E(FF(q))|*P = O, hence k*P = l*|E(FF(q))|*P. Thus kP.z_cord = 0 (mod q), and the unknownn factor of N (q) can be recovered by taking gcd(kP.z_cord, N). Stage 2 : This is a continuation of Stage 1 if k*P != O. The idea utilize the fact that even if kP != 0, the value of k might miss just one large prime divisor of |E(FF(q))|. In this case we only need to compute the scalar multiplication by p to get p*k*P = O. Here a second bound B2 restrict the size of possible values of p. Parameters ========== n : Number to be Factored B1 : Stage 1 Bound B2 : Stage 2 Bound max_curve : Maximum number of curves generated References ========== .. [1] Carl Pomerance and Richard Crandall "Prime Numbers: A Computational Perspective" (2nd Ed.), page 344 """ from sympy import gcd, mod_inverse, sqrt n = as_int(n) if B1 % 2 != 0 or B2 % 2 != 0: raise ValueError("The Bounds should be an even integer") sieve.extend(B2) if isprime(n): return n curve = 0 D = int(sqrt(B2)) beta = [0]*(D + 1) S = [0]*(D + 1) k = 1 for p in sieve.primerange(1, B1 + 1): k *= pow(p, integer_log(B1, p)[0]) g = 1 while(curve <= max_curve): curve += 1 #Suyama's Paramatrization sigma = rgen.randint(6, n - 1) u = (sigma*sigma - 5) % n v = (4*sigma) % n diff = v - u u_3 = pow(u, 3, n) try: C = (pow(diff, 3, n)*(3*u + v)*mod_inverse(4*u_3*v, n) - 2) % n except ValueError: #If the mod_inverse(4*u_3*v, n) doesn't exist return gcd(4*u_3*v, n) a24 = (C + 2)*mod_inverse(4, n) % n Q = Point(u_3 , pow(v, 3, n), a24, n) Q = Q.mont_ladder(k) g = gcd(Q.z_cord, n) #Stage 1 factor if g != 1 and g != n: return g #Stage 1 failure. Q.z = 0, Try another curve elif g == n: continue #Stage 2 - Improved Standard Continuation S[1] = Q.double() S[2] = S[1].double() beta[1] = (S[1].x_cord*S[1].z_cord) % n beta[2] = (S[2].x_cord*S[2].z_cord) % n for d in range(3, D + 1): S[d] = S[d - 1].add(S[1], S[d - 2]) beta[d] = (S[d].x_cord*S[d].z_cord) % n g = 1 B = B1 - 1 T = Q.mont_ladder(B - 2*D) R = Q.mont_ladder(B) for r in range(B, B2, 2*D): alpha = (R.x_cord*R.z_cord) % n for q in sieve.primerange(r + 2, r + 2*D + 1): delta = (q - r) // 2 f = (R.x_cord - S[d].x_cord)*(R.z_cord + S[d].z_cord) -\ alpha + beta[delta] g = (g*f) % n #Swap T, R = R, R.add(S[D], T) g = gcd(n, g) #Stage 2 Factor found if g != 1 and g != n: return g #ECM failed, Increase the bounds raise ValueError("Increase the bounds")
def ConcatenatingPrimeTest(a,b): if (isprime(int(str(a+b))) and isprime(int(str(b+a)))): return True return False
from sympy.ntheory import isprime from sympy import sieve limit = 1000 maxi, max_a, max_b = 0, 0, 0 for a, b in ((a, b) for a in xrange(-limit + 1, limit, 2) for b in sieve.primerange(2, limit)): n = 0 while isprime(n**2 + a * n + b): n += 1 if maxi < n: maxi, max_a, max_b = n, a, b print max_a * max_b
def test_elgamal_private_key(): a, b, _ = elgamal_private_key(digit=100) assert isprime(a) assert is_primitive_root(b, a) assert len(bin(a)) >= 102
for x in range(1, m): if ((e % m) * (x % m)) % m == 1: return x return -1 # Euclid's algorithm to find GCD def gcd(a, b): while b != 0: a, b = b, a % b return a minPrime = 0 maxPrime = 1000 cached_primes = [i for i in range(minPrime, maxPrime) if nt.isprime(i)] # Generate 2 random primes approximately of equal size (bits) p = random.choice([i for i in cached_primes if 100 < i < 200]) q = random.choice([i for i in cached_primes if 100 < i < 200]) n = p * q # Totient of n m = (p - 1) * (q - 1) # Choosing e, 1 < e < m such that gcd(e, m) = 1 e = random.randrange(1, m) g = gcd(e, m) # Verify whether gcd(e, m) = 1 while g != 1:
def is_attractive(what): factors = factorint(int(what)) return (isprime(sum(factors.values())))
''' I didnt write this but it's cool ''' import sympy.ntheory as spn import networkx as nx prime_range = list(spn.generate.primerange(1, 10000)) G = nx.Graph() for prime in prime_range: G.add_node(prime) for prime1 in prime_range: for prime2 in prime_range: if prime2 > prime1: concatenated = [int(str(prime1) + str(prime2)) ] + [int(str(prime2) + str(prime1))] if all([spn.isprime(x) for x in concatenated]): G.add_edge(prime1, prime2) print(min([sum(l) for l in nx.find_cliques(G) if len(l) == 5]))
def _(expr, assumptions): return isprime(expr)
def zzx_zassenhaus(f): """Factor square-free polynomials over Z[x]. """ n = zzx_degree(f) if n == 1: return [f] A = zzx_max_norm(f) b = zzx_LC(f) B = abs(int(sqrt(n+1)*2**n*A*b)) C = (n+1)**(2*n)*A**(2*n-1) gamma = int(ceil(2*log(C, 2))) prime_max = int(2*gamma*log(gamma)) for p in xrange(3, prime_max+1): if not isprime(p) or b % p == 0: continue F = gf_from_int_poly(f, p) if gf_sqf_p(F, p): break l = int(ceil(log(2*B + 1, p))) modular = [] for ff in gf_factor_sqf(F, p)[1]: modular.append(gf_to_int_poly(ff, p)) g = zzx_hensel_lift(p, f, modular, l) T = set(range(len(g))) factors, s = [], 1 while 2*s <= len(T): for S in subsets(T, s): G, H = [b], [b] S = set(S) for i in S: G = zzx_mul(G, g[i]) for i in T-S: H = zzx_mul(H, g[i]) G = zzx_trunc(G, p**l) H = zzx_trunc(H, p**l) G_norm = zzx_l1_norm(G) H_norm = zzx_l1_norm(H) if G_norm*H_norm <= B: T = T - S G = zzx_primitive(G)[1] f = zzx_primitive(H)[1] factors.append(G) b = zzx_LC(f) break else: s += 1 return factors + [f]
f48acce6f24239f6c04028788135cd\ 88c3d15be0f2ebb7de9e9c19a7a930\ 37005ee0a9a640bada332ec0d05ee9\ f08a832354a0487a927d5e88066e25\ 69e6c5d4688e422bfa0b27c6171c6d\ 7bf029bfd9165752af19aa71b33a1e\ a70b6c371fb21e47f527d80b7d04f5\ 82ad9f9935af723682dc01ca988062\ 1870decb7ad15648cdf4ef153016f3\ e6d87933b8ec54cfa1fdf87c467020\ a3e753""" e = 0x10001 n = int(modulus, 16) f = open("./possibleprimes.txt") for line in f: p = int(line, 16) q = n // p if (isprime(q)): break phi = (p - 1) * (q - 1) d = modinv(e, phi) dp = modinv(e, (p - 1)) dq = modinv(e, (q - 1)) qi = modinv(q, p) key = pempriv(n, e, d, p, q, dp, dq, qi) print(key)
def keygen(k, t, l, save_dir, save_in_file=True, gen_dlut=False): # generate distinct primes vp and vq vp = gensafeprime.generate(t) while (1): vq = gensafeprime.generate(t) if vp != vq: break # generate u to be the prime just greater than 2^l+2 u = nextprime(pow(2, l + 2)) # generate prime p s.t. vp | p-1 and u | p-1 print("Generating p....") while (1): temp1 = 2 * u * vp sz = k // 2 - temp1.bit_length() prand = gensafeprime.generate(sz) p = temp1 * prand + 1 if isprime(p): break print("Generating q....") # generate prime q s.t. vq | q-1 and u | q-1 while (1): temp1 = 2 * u * vq sz = k // 2 - temp1.bit_length() qrand = gensafeprime.generate(sz) q = temp1 * qrand + 1 if isprime(q): break # calc n n = p * q # finding h partials_p = [2 * u * vp, 2 * u * prand, 2 * vp * prand, prand * vp * u] while (1): hrandp = random.randint(0, p - 1) if (hrandp == 1 or math.gcd(hrandp, p) != 1): continue f = False for prod in partials_p: f = f | (pow(hrandp, prod, p) == 1) if (f): break if (not f): break partials_q = [2 * u * vq, 2 * u * qrand, 2 * vq * qrand, qrand * vq * u] while (1): hrandq = random.randint(0, q - 1) if (hrandq == 1 or math.gcd(hrandq, q) != 1): continue f = False for prod in partials_q: f = f | (pow(hrandq, prod, q) == 1) if (f): break if (not f): break hrand = (hrandp * q * mod_inverse(q, p) + hrandq * p * mod_inverse(p, q)) % n h = pow(hrand, 2 * u * prand * qrand, n) #finding g partials_p = [2 * u * vp, 2 * u * prand, 2 * vp * prand, prand * vp * u] while (1): grandp = random.randint(0, p - 1) if (grandp == 1 or math.gcd(grandp, p) != 1): continue f = False for prod in partials_p: f = f | (pow(grandp, prod, p) == 1) # modp or modp-1 if (f): break if (not f): break partials_q = [2 * u * vq, 2 * u * qrand, 2 * vq * qrand, qrand * vq * u] while (1): grandq = random.randint(0, q - 1) if (grandq == 1 or math.gcd(grandq, q) != 1): continue f = False for prod in partials_q: f = f | (pow(grandq, prod, q) == 1) # modp or modp-1 if (f): break if (not f): break grand = (hrandp * q * mod_inverse(q, p) + hrandq * p * mod_inverse(p, q)) % n g = pow(grand, 2 * prand * qrand, n) priv, pub = {}, {} priv['p'], priv['q'], priv['vp'], priv['vq'] = p, q, \ vp, vq pub['n'], pub['g'], pub['h'], pub['u'], pub['t'] = n, g, \ h, u, t if (gen_dlut): print("Generating dlut....") priv['dlut'] = [] for i in range(pub['u']): if (i % 10000 == 0): print(i) priv['dlut'].append(pow(pub['g'], priv['vp'] * i, priv['p'])) priv['dlut'] = np.array(priv['dlut']) if (save_in_file): np.save(os.path.join(save_dir, "priv.npy"), priv) np.save(os.path.join(save_dir, "pub.npy"), pub) return priv, pub
counter = 0 cur_num = 1 while counter < amount: enclosed_num = "{0:b}".format(cur_num) while len(enclosed_num) != length - 2: enclosed_num = "0" + enclosed_num enclosed_num = "1" + enclosed_num + "1" check = True bases = [] for i in range(2, 11): base = int(enclosed_num, i) bases.append(base) if isprime(base): check = False break #print(len(bases)) if check == True: print(enclosed_num, end="") output.write(enclosed_num) for base in bases: if divisor_count(base) == 2: print("dafuq") print(' ', end="") print(primefactors(base)[0], end="") output.write(" ") output.write(str(primefactors(base)[0])) print()
def dup_zz_zassenhaus(f, K): """Factor primitive square-free polynomials in `Z[x]`. """ n = dup_degree(f) if n == 1: return [f] fc = f[-1] A = dup_max_norm(f, K) b = dup_LC(f, K) B = int(abs(K.sqrt(K(n + 1))*2**n*A*b)) C = int((n + 1)**(2*n)*A**(2*n - 1)) gamma = int(_ceil(2*_log(C, 2))) bound = int(2*gamma*_log(gamma)) a = [] # choose a prime number `p` such that `f` be square free in Z_p # if there are many factors in Z_p, choose among a few different `p` # the one with fewer factors for px in range(3, bound + 1): if not isprime(px) or b % px == 0: continue px = K.convert(px) F = gf_from_int_poly(f, px) if not gf_sqf_p(F, px, K): continue fsqfx = gf_factor_sqf(F, px, K)[1] a.append((px, fsqfx)) if len(fsqfx) < 15 or len(a) > 4: break p, fsqf = min(a, key=lambda x: len(x[1])) l = int(_ceil(_log(2*B + 1, p))) modular = [gf_to_int_poly(ff, p) for ff in fsqf] g = dup_zz_hensel_lift(p, f, modular, l, K) sorted_T = range(len(g)) T = set(sorted_T) factors, s = [], 1 pl = p**l while 2*s <= len(T): for S in subsets(sorted_T, s): # lift the constant coefficient of the product `G` of the factors # in the subset `S`; if it is does not divide `fc`, `G` does # not divide the input polynomial if b == 1: q = 1 for i in S: q = q*g[i][-1] q = q % pl if not _test_pl(fc, q, pl): continue else: G = [b] for i in S: G = dup_mul(G, g[i], K) G = dup_trunc(G, pl, K) G = dup_primitive(G, K)[1] q = G[-1] if q and fc % q != 0: continue H = [b] S = set(S) T_S = T - S if b == 1: G = [b] for i in S: G = dup_mul(G, g[i], K) G = dup_trunc(G, pl, K) for i in T_S: H = dup_mul(H, g[i], K) H = dup_trunc(H, pl, K) G_norm = dup_l1_norm(G, K) H_norm = dup_l1_norm(H, K) if G_norm*H_norm <= B: T = T_S sorted_T = [i for i in sorted_T if i not in S] G = dup_primitive(G, K)[1] f = dup_primitive(H, K)[1] factors.append(G) b = dup_LC(f, K) break else: s += 1 return factors + [f]
def check(p, q, e): phi = (p - 1) * (q - 1) return p != q and isprime(p) and isprime(q) and phi > e and igcd(phi, e) == 1
def dup_zz_zassenhaus(f, K): """Factor primitive square-free polynomials in `Z[x]`. """ n = dup_degree(f) if n == 1: return [f] A = dup_max_norm(f, K) b = dup_LC(f, K) B = int(abs(K.sqrt(K(n+1))*2**n*A*b)) C = int((n+1)**(2*n)*A**(2*n-1)) gamma = int(ceil(2*log(C, 2))) bound = int(2*gamma*log(gamma)) for p in xrange(3, bound+1): if not isprime(p) or b % p == 0: continue p = K.convert(p) F = gf_from_int_poly(f, p) if gf_sqf_p(F, p, K): break l = int(ceil(log(2*B + 1, p))) modular = [] for ff in gf_factor_sqf(F, p, K)[1]: modular.append(gf_to_int_poly(ff, p)) g = dup_zz_hensel_lift(p, f, modular, l, K) T = set(range(len(g))) factors, s = [], 1 while 2*s <= len(T): for S in subsets(T, s): G, H = [b], [b] S = set(S) for i in S: G = dup_mul(G, g[i], K) for i in T-S: H = dup_mul(H, g[i], K) G = dup_trunc(G, p**l, K) H = dup_trunc(H, p**l, K) G_norm = dup_l1_norm(G, K) H_norm = dup_l1_norm(H, K) if G_norm*H_norm <= B: T = T - S G = dup_primitive(G, K)[1] f = dup_primitive(H, K)[1] factors.append(G) b = dup_LC(f, K) break else: s += 1 return factors + [f]
def combo(a, b): return (isprime(int(a * (10**(floor(log10(b)) + 1)) + b)) and isprime(int(b * (10**(floor(log10(a)) + 1)) + a)))
import math from sympy.ntheory import isprime, factorint start = 12345678987654321 for i in range(0, 1000, 2): if isprime(start + i): break p1 = start + i print(p1) start = 23456789876543212 for i in range(1, 1000, 2): if isprime(start + i): break p2 = start + i print(p2) N = p1 * p2 print(N) print(isprime(N)) if False: print(factorint(N)) def L(n, a, c): """ """ ln = math.log(n) lln = math.log(ln) p = c * (ln**a) * (lln**(1 - a)) return math.exp(p)
def phi(n): if isprime(n): return n - 1 factors, prod = factorint(n), 1 for factor, exp in factors.items(): prod *= factor**(exp - 1) * (factor - 1) return prod
def largest_pandigital_prime(n): for tuple in permutations(reversed(range(1, n + 1))): number = tuple_to_number(tuple) if isprime(number): return number return None
def dup_zz_zassenhaus(f, K): """Factor primitive square-free polynomials in `Z[x]`. """ n = dup_degree(f) if n == 1: return [f] A = dup_max_norm(f, K) b = dup_LC(f, K) B = int(abs(K.sqrt(K(n + 1)) * 2**n * A * b)) C = int((n + 1)**(2 * n) * A**(2 * n - 1)) gamma = int(_ceil(2 * _log(C, 2))) bound = int(2 * gamma * _log(gamma)) for p in xrange(3, bound + 1): if not isprime(p) or b % p == 0: continue p = K.convert(p) F = gf_from_int_poly(f, p) if gf_sqf_p(F, p, K): break l = int(_ceil(_log(2 * B + 1, p))) modular = [] for ff in gf_factor_sqf(F, p, K)[1]: modular.append(gf_to_int_poly(ff, p)) g = dup_zz_hensel_lift(p, f, modular, l, K) sorted_T = range(len(g)) T = set(sorted_T) factors, s = [], 1 while 2 * s <= len(T): for S in subsets(sorted_T, s): G, H = [b], [b] S = set(S) T_S = T - S for i in S: G = dup_mul(G, g[i], K) for i in T_S: H = dup_mul(H, g[i], K) G = dup_trunc(G, p**l, K) H = dup_trunc(H, p**l, K) G_norm = dup_l1_norm(G, K) H_norm = dup_l1_norm(H, K) if G_norm * H_norm <= B: T = T_S sorted_T = [i for i in sorted_T if i not in S] G = dup_primitive(G, K)[1] f = dup_primitive(H, K)[1] factors.append(G) b = dup_LC(f, K) break else: s += 1 return factors + [f]
def primeOrComposite(num1): if isprime(num1) == True: print(num1, "is a prime number") elif isprime(num1) == False: print(num1, "is a composite number")
def strong_harshad(numero): xifrat = suma_digits(numero) if numero%xifrat != 0: return False candidat = numero//xifrat return isprime(candidat)