def ID41(backlist, frontlist): backlength = len(backlist) frontlength = len(frontlist) if backlength == 2: backlist[0], backlist[1] = backlist[1], backlist[0] numlist = frontlist + backlist number = '' for i in numlist: number += str(i) number = int(number) if isprime(number): print('The number is', number) return 1 backlist[0], backlist[1] = backlist[1], backlist[0] return else: templist = backlist for j in templist: index = templist.index(j) frontlist.append(j) backlist.remove(j) ID41(backlist, frontlist) numlist = frontlist + backlist number = '' for i in numlist: number += str(i) number = int(number) if isprime(number): print('The number is', number) return 1 backlist.insert(index, j) frontlist.remove(j)
def prevprime(n): """ Return the largest prime smaller than n. Potential primes are located at 6*j +/- 1. >>> from sympy import prevprime >>> [(i, prevprime(i)) for i in range(10, 15)] [(10, 7), (11, 7), (12, 11), (13, 11), (14, 13)] See Also ======== nextprime : Return the ith prime greater than n primerange : Generates all primes in a given range """ n = int_tested(n, strict=False) if n < 3: raise ValueError("no preceding primes") if n < 8: return {3: 2, 4: 3, 5: 3, 6: 5, 7: 5}[n] nn = 6 * (n // 6) if n - nn <= 1: n = nn - 1 if isprime(n): return n n -= 4 else: n = nn + 1 while 1: if isprime(n): return n n -= 2 if isprime(n): return n n -= 4
def prevprime(n): """ Return the largest prime smaller than n. Potential primes are located at 6*j +/- 1. >>> from sympy import prevprime >>> [(i, prevprime(i)) for i in range(10, 15)] [(10, 7), (11, 7), (12, 11), (13, 11), (14, 13)] """ n = int(n) if n < 3: raise ValueError("no preceding primes") if n < 8: return {3: 2, 4: 3, 5: 3, 6: 5, 7: 5}[n] nn = 6 * (n // 6) if n - nn <= 1: n = nn - 1 if isprime(n): return n n -= 4 else: n = nn + 1 while 1: if isprime(n): return n n -= 2 if isprime(n): return n n -= 4
def nextprime(n, ith=1): """ Return the ith prime greater than n. i must be an integer. Notes ===== Potential primes are located at 6*j +/- 1. This property is used during searching. >>> from sympy import nextprime >>> [(i, nextprime(i)) for i in range(10, 15)] [(10, 11), (11, 13), (12, 13), (13, 17), (14, 17)] >>> nextprime(2, ith=2) # the 2nd prime after 2 5 See Also ======== prevprime : Return the largest prime smaller than n primerange : Generate all primes in a given range """ n = int(n) i = as_int(ith) if i > 1: pr = n j = 1 while 1: pr = nextprime(pr) j += 1 if j > i: break return pr if n < 2: return 2 if n < 7: return {2: 3, 3: 5, 4: 5, 5: 7, 6: 7}[n] nn = 6*(n//6) if nn == n: n += 1 if isprime(n): return n n += 4 elif n - nn == 5: n += 2 if isprime(n): return n n += 4 else: n = nn + 5 while 1: if isprime(n): return n n += 2 if isprime(n): return n n += 4
def prevprime(n): """ Return the largest prime smaller than n. Potential primes are located at 6*j +/- 1. >>> from sympy import prevprime >>> [(i, prevprime(i)) for i in range(10, 15)] [(10, 7), (11, 7), (12, 11), (13, 11), (14, 13)] See Also ======== nextprime, primerange """ n = int(n) if n < 3: raise ValueError("no preceding primes") if n < 8: return {3: 2, 4: 3, 5: 3, 6: 5, 7: 5}[n] nn = 6*(n//6) if n - nn <= 1: n = nn - 1 if isprime(n): return n n -= 4 else: n = nn + 1 while 1: if isprime(n): return n n -= 2 if isprime(n): return n n -= 4
def nextprime(n, i=1): """ Return the ith prime greater than n. Potential primes are located at 6*j +/- 1. >>> from sympy import nextprime >>> [(i, nextprime(i)) for i in range(10, 15)] [(10, 11), (11, 13), (12, 13), (13, 17), (14, 17)] >>> nextprime(2, i=2) # the 2nd prime after 2 5 See Also ======== prevprime : Return the largest prime smaller than n primerange : Generate all primes in a given range """ n = int_tested(n, strict=False) if i > 1: pr = n j = 1 while 1: pr = nextprime(pr) j += 1 if j > i: break return pr n = int(n) if n < 2: return 2 if n < 7: return {2: 3, 3: 5, 4: 5, 5: 7, 6: 7}[n] nn = 6*(n//6) if nn == n: n += 1 if isprime(n): return n n += 4 elif n - nn == 5: n += 2 if isprime(n): return n n += 4 else: n = nn + 5 while 1: if isprime(n): return n n += 2 if isprime(n): return n n += 4
def nextprime(n, i=1): """ Return the ith prime greater than n. Potential primes are located at 6*j +/- 1. >>> from sympy import nextprime >>> [(i, nextprime(i)) for i in range(10, 15)] [(10, 11), (11, 13), (12, 13), (13, 17), (14, 17)] >>> nextprime(2, i=2) # the 2nd prime after 2 5 See Also ======== prevprime : Return the largest prime smaller than n primerange : Generate all primes in a given range """ n = int_tested(n, strict=False) if i > 1: pr = n j = 1 while 1: pr = nextprime(pr) j += 1 if j > i: break return pr n = int(n) if n < 2: return 2 if n < 7: return {2: 3, 3: 5, 4: 5, 5: 7, 6: 7}[n] nn = 6 * (n // 6) if nn == n: n += 1 if isprime(n): return n n += 4 elif n - nn == 5: n += 2 if isprime(n): return n n += 4 else: n = nn + 5 while 1: if isprime(n): return n n += 2 if isprime(n): return n n += 4
def is_quad_residue(a, p): """ Returns True if ``a`` (mod ``p``) is in the set of squares mod ``p``, i.e a % p in set([i**2 % p for i in range(p)]). If ``p`` is an odd prime, an iterative method is used to make the determination: >>> from sympy.ntheory import is_quad_residue >>> list(set([i**2 % 7 for i in range(7)])) [0, 1, 2, 4] >>> [j for j in range(7) if is_quad_residue(j, 7)] [0, 1, 2, 4] See Also ======== legendre_symbol, jacobi_symbol """ a, p = as_int(a), as_int(p) if p < 1: raise ValueError('p must be > 0') if a >= p or a < 0: a = a % p if a < 2 or p < 3: return True if not isprime(p): if p % 2 and jacobi_symbol(a, p) == -1: return False for i in range(2, p // 2 + 1): if i**2 % p == a: return True return False return pow(a, (p - 1) // 2, p) == 1
def legendre_symbol(a, p): """ Returns 0 if a is multiple of p, 1 if a is a quadratic residue of p, else -1 p should be an odd prime by definition **Examples** >>> from sympy.ntheory import legendre_symbol >>> [legendre_symbol(i, 7) for i in range(7)] [0, 1, 1, -1, 1, -1, -1] >>> list(set([i**2 % 7 for i in range(7)])) [0, 1, 2, 4] """ a, p = int_tested(a, p) if not isprime(p) or p == 2: raise ValueError("p should be an odd prime") _, a = divmod(a, p) if not a: return 0 if is_quad_residue(a, p): return 1 else: return -1
def nextprime(n): """Return the smallest prime greater than n.""" n = max(n, 0) while 1: n += 1 if isprime(n): return n
def _check_termination(factors, n, verbose=False): """ Helper function for integer factorization. Checks if ``n`` is a prime or a perfect power, and in those cases updates the factorization and raises ``StopIteration``. """ if verbose: print "Checking if remaining factor terminates the factorization" n = int(n) if n == 1: raise StopIteration p = perfect_power(n) if p: base, exp = p if verbose: print "-- Remaining factor is a perfect power: %i ** %i" % (base, exp) for b, e in factorint(base).iteritems(): factors[b] = exp * e raise StopIteration if isprime(n): if verbose: print "Remaining factor", n, "is prime" factors[n] = 1 raise StopIteration
def primefactors(n, limit=None, verbose=False): """Return a sorted list of n's prime factors, ignoring multiplicity and any composite factor that remains if the limit was set too low for complete factorization. Unlike factorint(), primefactors() does not return -1 or 0. Examples ======== >>> from sympy.ntheory import primefactors, factorint, isprime >>> primefactors(6) [2, 3] >>> primefactors(-5) [5] >>> sorted(factorint(123456).items()) [(2, 6), (3, 1), (643, 1)] >>> primefactors(123456) [2, 3, 643] >>> sorted(factorint(10000000001, limit=200).items()) [(101, 1), (99009901, 1)] >>> isprime(99009901) False >>> primefactors(10000000001, limit=300) [101] """ n = int(n) s = [] factors = sorted(factorint(n, limit=limit, verbose=verbose).keys()) s = [f for f in factors[:-1:] if f not in [-1, 0, 1]] if factors and isprime(factors[-1]): s += [factors[-1]] return s
def is_quad_residue(a, p): """ Returns True if ``a`` (mod ``p``) is in the set of squares mod ``p``, i.e a % p in set([i**2 % p for i in range(p)]). If ``p`` is an odd prime, an iterative method is used to make the determination: >>> from sympy.ntheory import is_quad_residue >>> list(set([i**2 % 7 for i in range(7)])) [0, 1, 2, 4] >>> [j for j in range(7) if is_quad_residue(j, 7)] [0, 1, 2, 4] See Also ======== legendre_symbol, jacobi_symbol """ a, p = as_int(a), as_int(p) if p < 1: raise ValueError('p must be > 0') if a >= p or a < 0: a = a % p if a < 2 or p < 3: return True if not isprime(p): if p % 2 and jacobi_symbol(a, p) == -1: return False for i in range(2, p//2 + 1): if i**2 % p == a: return True return False return pow(a, (p - 1) // 2, p) == 1
def legendre_symbol(a, p): """ Returns ======= 1. 0 if a is multiple of p 2. 1 if a is a quadratic residue of p 3. -1 otherwise p should be an odd prime by definition Examples ======== >>> from sympy.ntheory import legendre_symbol >>> [legendre_symbol(i, 7) for i in range(7)] [0, 1, 1, -1, 1, -1, -1] >>> list(set([i**2 % 7 for i in range(7)])) [0, 1, 2, 4] See Also ======== is_quad_residue, jacobi_symbol """ a, p = int_tested(a, p) if not isprime(p) or p == 2: raise ValueError("p should be an odd prime") _, a = divmod(a, p) if not a: return 0 if is_quad_residue(a, p): return 1 else: return -1
def primefactors(n, limit=None, verbose=False): """Return a sorted list of n's prime factors, ignoring multiplicity and any composite factor that remains if the limit was set too low for complete factorization. Unlike factorint(), primefactors() does not return -1 or 0. Example usage ============= >>> from sympy.ntheory import primefactors, factorint, isprime >>> primefactors(6) [2, 3] >>> primefactors(-5) [5] >>> sorted(factorint(123456).items()) [(2, 6), (3, 1), (643, 1)] >>> primefactors(123456) [2, 3, 643] >>> sorted(factorint(10000000001, limit=200).items()) [(101, 1), (99009901, 1)] >>> isprime(99009901) False >>> primefactors(10000000001, limit=300) [101] """ n = int(n) s = [] factors = sorted(factorint(n, limit=limit, verbose=verbose).keys()) s = [f for f in factors[:-1:] if f not in [-1, 0, 1]] if factors and isprime(factors[-1]): s += [factors[-1]] return s
def _check_termination(factors, n, limitp1, use_trial, use_rho, use_pm1, verbose): """ Helper function for integer factorization. Checks if ``n`` is a prime or a perfect power, and in those cases updates the factorization and raises ``StopIteration``. """ if verbose: print 'Check for termination' # since we've already been factoring there is no need to do # simultaneous factoring with the power check p = perfect_power(n, factor=False) if p is not False: base, exp = p if limitp1: limit = limitp1 - 1 else: limit = limitp1 facs = factorint(base, limit, use_trial, use_rho, use_pm1, verbose=False) for b, e in facs.items(): if verbose: print factor_msg % (b, e) factors[b] = exp*e raise StopIteration if isprime(n): factors[int(n)] = 1 raise StopIteration if n == 1: raise StopIteration
def nextprime(n, i=1): """ Return the ith prime greater than n. Potential primes are located at 6*j +/- 1. >>> from sympy import nextprime >>> [(i, nextprime(i)) for i in range(10, 15)] [(10, 11), (11, 13), (12, 13), (13, 17), (14, 17)] >>> nextprime(2, i=2) # the 2nd prime after 2 5 """ if i > 1: pr = n j = 1 while 1: pr = nextprime(pr) j += 1 if j > i: break return pr n = int(n) if n < 2: return 2 if n < 7: return {2: 3, 3: 5, 4: 5, 5: 7, 6: 7}[n] nn = 6*(n//6) if nn == n: n += 1 if isprime(n): return n n += 4 elif n - nn == 5: n += 2 if isprime(n): return n n += 4 else: n = nn + 5 while 1: if isprime(n): return n n += 2 if isprime(n): return n n += 4
def nextprime(n, i=1): """ Return the ith prime greater than n. Potential primes are located at 6*j +/- 1. >>> from sympy import nextprime >>> [(i, nextprime(i)) for i in range(10, 15)] [(10, 11), (11, 13), (12, 13), (13, 17), (14, 17)] >>> nextprime(2, i=2) # the 2nd prime after 2 5 """ if i > 1: pr = n j = 1 while 1: pr = nextprime(pr) j += 1 if j > i: break return pr n = int(n) if n < 2: return 2 if n < 7: return {2: 3, 3: 5, 4: 5, 5: 7, 6: 7}[n] nn = 6 * (n // 6) if nn == n: n += 1 if isprime(n): return n n += 4 elif n - nn == 5: n += 2 if isprime(n): return n n += 4 else: n = nn + 5 while 1: if isprime(n): return n n += 2 if isprime(n): return n n += 4
def prevprime(n): """Return the largest prime smaller than n.""" if n < 3: raise ValueError, "no preceding primes" while 1: n -= 1 if isprime(n): return n
def prevprime(n): """Return the largest prime smaller than n.""" if n < 3: raise ValueError("no preceding primes") while 1: n -= 1 if isprime(n): return n
def prevprime(n): """ Return the largest prime smaller than n. Notes ===== Potential primes are located at 6*j +/- 1. This property is used during searching. >>> from sympy import prevprime >>> [(i, prevprime(i)) for i in range(10, 15)] [(10, 7), (11, 7), (12, 11), (13, 11), (14, 13)] See Also ======== nextprime : Return the ith prime greater than n primerange : Generates all primes in a given range """ from sympy.functions.elementary.integers import ceiling # wrapping ceiling in int will raise an error if there was a problem # determining whether the expression was exactly an integer or not n = int(ceiling(n)) if n < 3: raise ValueError("no preceding primes") if n < 8: return {3: 2, 4: 3, 5: 3, 6: 5, 7: 5}[n] nn = 6*(n//6) if n - nn <= 1: n = nn - 1 if isprime(n): return n n -= 4 else: n = nn + 1 while 1: if isprime(n): return n n -= 2 if isprime(n): return n n -= 4
def legendre_symbol(a,p): """ return 1 if a is a quadratic residue of p else return -1 p should be an odd prime by definition """ assert isprime(p) and p!=2,"p should be an odd prime" assert igcd(a,p)==1,"The two numbers should be relatively prime" if a>p: a=a%p if is_quad_residue(a,p)==True: return 1 else : return -1
def legendre_symbol(a, p): """ return 1 if a is a quadratic residue of p else return -1 p should be an odd prime by definition """ assert isprime(p) and p != 2, "p should be an odd prime" assert igcd(a, p) == 1, "The two numbers should be relatively prime" if a > p: a = a % p if is_quad_residue(a, p) == True: return 1 else: return -1
def is_quad_residue(a,p): """ returns True if a is a quadratic residue of p p should be a prime and a should be relatively prime to p """ assert isprime(p) and p!=2,"p should be an odd prime" assert igcd(a,p)==1,"The two numbers should be relatively prime" if a>p: a=a%p rem=(a**((p-1)//2))%p # a^(p-1 / 2) % p if rem==1: return True else : return False
def is_quad_residue(a, p): """ returns True if a is a quadratic residue of p p should be a prime and a should be relatively prime to p """ assert isprime(p) and p != 2, "p should be an odd prime" assert igcd(a, p) == 1, "The two numbers should be relatively prime" if a > p: a = a % p rem = (a**((p - 1) // 2)) % p # a^(p-1 / 2) % p if rem == 1: return True else: return False
def divisors(n): """ Return a list of all positive integer divisors of n. >>> divisors(24) [1, 2, 3, 4, 6, 8, 12, 24] """ n = abs(n) if isprime(n): return [1, n] s = [] for i in xrange(1, n+1): if n % i == 0: s += [i] return s
def divisors(n): """ Return a list of all positive integer divisors of n. >>> divisors(24) [1, 2, 3, 4, 6, 8, 12, 24] """ n = abs(n) if isprime(n): return [1, n] s = [] for i in xrange(1, n + 1): if n % i == 0: s += [i] return s
def legendre_symbol(a, p): """ return 1 if a is a quadratic residue of p, 0 if a is multiple of p, else return -1 p should be an odd prime by definition """ if not isprime(p) or p == 2: raise ValueError("p should be an odd prime") _, a = divmod(a, p) if not a: return 0 if is_quad_residue(a, p): return 1 else: return -1
def legendre_symbol(a, p): """ return 1 if a is a quadratic residue of p else return -1 p should be an odd prime by definition """ if not isprime(p) or p == 2: raise ValueError("p should be an odd prime") if igcd(a, p) != 1: raise ValueError("The two numbers should be relatively prime") if a > p: a = a % p if is_quad_residue(a, p): return 1 else: return -1
def divisors(n, generator=False): r""" Return all divisors of n sorted from 1..n by default. If generator is True an unordered generator is returned. The number of divisors of n can be quite large if there are many prime factors (counting repeated factors). If only the number of factors is desired use divisor_count(n). Examples ======== >>> from sympy import divisors, divisor_count >>> divisors(24) [1, 2, 3, 4, 6, 8, 12, 24] >>> divisor_count(24) 8 >>> list(divisors(120, generator=True)) [1, 2, 4, 8, 3, 6, 12, 24, 5, 10, 20, 40, 15, 30, 60, 120] This is a slightly modified version of Tim Peters referenced at: http://stackoverflow.com/questions/1010381/python-factorization See Also ======== primefactors, factorint, divisor_count """ n = int(abs(n)) if isprime(n): return [1, n] elif n == 1: return [1] elif n == 0: return [] else: rv = _divisors(n) if not generator: return sorted(rv) return rv
def divisors(n, generator=False): r""" Return all divisors of n sorted from 1..n by default. If generator is True an unordered generator is returned. The number of divisors of n can be quite large if there are many prime factors (counting repeated factors). If only the number of factors is desired use divisor_count(n). Examples ======== >>> from sympy import divisors, divisor_count >>> divisors(24) [1, 2, 3, 4, 6, 8, 12, 24] >>> divisor_count(24) 8 >>> list(divisors(120, generator=True)) [1, 2, 4, 8, 3, 6, 12, 24, 5, 10, 20, 40, 15, 30, 60, 120] This is a slightly modified version of Tim Peters referenced at: http://stackoverflow.com/questions/1010381/python-factorization See Also ======== primefactors, factorint, divisor_count """ n = abs(n) if isprime(n): return [1, n] elif n == 1: return [1] elif n == 0: return [] else: rv = _divisors(n) if not generator: return sorted(rv) return rv
def trial(n, candidates=None): """ Factor n as far as possible through trial division, taking candidate factors from the given list. If no list of candidate factors is given, the prime numbers in the interval [2, sqrt(n)] are used, which guarantees a complete factorization. The returned value is a list [(p1, e1), ...] such that n = p1**e1 * p2**e2 * ... If n could not be completely factored using numbers in the given range, the last p might be composite. Example usage ============= A complete factorization: >>> trial(36960) [(2, 5), (3, 1), (5, 1), (7, 1), (11, 1)] This won't find the factors 7 and 11: >>> trial(36960, [2, 3, 5]) [(2, 5), (3, 1), (5, 1), (77, 1)] """ if n == 1: return [] if candidates is None: candidates = sieve.primerange(2, int(n**0.5) + 1) factors = [] for k in candidates: m = multiplicity(k, n) if m != 0: n //= k**m factors = factors + [(k, m)] if isprime(n): return factors + [(int(n), 1)] elif n == 1: return factors return factors + [(int(n), 1)]
def trial(n, candidates=None): """ Factor n as far as possible through trial division, taking candidate factors from the given list. If no list of candidate factors is given, the prime numbers in the interval [2, sqrt(n)] are used, which guarantees a complete factorization. The returned value is a list [(p1, e1), ...] such that n = p1**e1 * p2**e2 * ... If n could not be completely factored using numbers in the given range, the last p might be composite. Example usage ============= A complete factorization: >>> trial(36960) [(2, 5), (3, 1), (5, 1), (7, 1), (11, 1)] This won't find the factors 7 and 11: >>> trial(36960, [2, 3, 5]) [(2, 5), (3, 1), (5, 1), (77, 1)] """ if n == 1: return [] if candidates is None: candidates = sieve.primerange(2, int(n**0.5)+1) factors = [] for k in candidates: m = multiplicity(k, n) if m != 0: n //= k**m factors = factors + [(k, m)] if isprime(n): return factors + [(int(n), 1)] elif n == 1: return factors return factors + [(int(n), 1)]
def primefactors(n, limit=None, verbose=False): """Return a list of n's prime factors, ignoring multiplicity. Unlike factorint(), primefactors() only returns prime numbers; i.e., it does not return -1 or 0, and if 'limit' is set too low for all factors to be found, composite factors are ignored. Example usage ============= >>> from sympy.ntheory import primefactors, factorint, isprime >>> primefactors(6) [2, 3] >>> primefactors(-5) [5] >>> sorted(factorint(123456).items()) [(2, 6), (3, 1), (643, 1)] >>> primefactors(123456) [2, 3, 643] >>> sorted(factorint(10000000001, limit=200).items()) [(101, 1), (99009901, 1)] >>> isprime(99009901) False >>> primefactors(10000000001, limit=300) [101] """ n = int(n) s = [] factors = sorted(factorint(n, limit=limit, verbose=verbose).items()) for p, _ in sorted(factors)[:-1:]: if p not in [-1, 0, 1]: s += [p] if isprime(factors[-1][0]): s += [factors[-1][0]] return s
def is_quad_residue(a, p): """ Returns True if ``a`` (mod ``p``) is in the set of squares mod ``p``, i.e a % p in set([i**2 % p for i in range(p)]). If ``p`` is an odd prime, an iterative method is used to make the determination. >>> from sympy.ntheory import is_quad_residue >>> list(set([i**2 % 7 for i in range(7)])) [0, 1, 2, 4] >>> [j for j in range(7) if is_quad_residue(j, 7)] [0, 1, 2, 4] """ a, p = int_tested(a, p) if p < 1: raise ValueError('p must be > 0') if a >= p or a < 0: a = a % p if a < 2 or p < 3: return True if not isprime(p): if p % 2 and jacobi_symbol(a, p) == -1: return False for i in range(2, p // 2 + 1): if i**2 % p == a: return True return False def square_and_multiply(a, n, p): if n == 1: return a elif n % 2 == 1: return ((square_and_multiply(a, n // 2, p)**2) * a) % p else: return (square_and_multiply(a, n // 2, p)**2) % p return (square_and_multiply(a, (p - 1) // 2, p) % p) == 1
def primefactors(n, limit=None, verbose=False): """Return a list of n's prime factors, ignoring multiplicity. Unlike factorint(), primefactors() only returns prime numbers; i.e., it does not return -1 or 0, and if 'limit' is set too low for all factors to be found, composite factors are ignored. Example usage ============= >>> primefactors(6) [2, 3] >>> primefactors(-5) [5] >>> sorted(factorint(123456).items()) [(2, 6), (3, 1), (643, 1)] >>> primefactors(123456) [2, 3, 643] >>> sorted(factorint(10000000001, limit=200).items()) [(101, 1), (99009901, 1)] >>> isprime(99009901) False >>> primefactors(10000000001, limit=300) [101] """ n = int(n) s = [] factors = sorted(factorint(n, limit=limit, verbose=verbose).items()) for p, _ in sorted(factors)[:-1:]: if p not in [-1, 0, 1]: s += [p] if isprime(factors[-1][0]): s += [factors[-1][0]] return s
def is_quad_residue(a, p): """ returns True if a is a quadratic residue of p p should be a prime and a should be relatively prime to p """ if not isprime(p) or p == 2: raise ValueError("p should be an odd prime") if igcd(a, p) != 1: raise ValueError("The two numbers should be relatively prime") if a > p: a = a % p def square_and_multiply(a, n, p): if n == 0: return 1 elif n == 1: return a elif n % 2 == 1: return ((square_and_multiply(a, n // 2, p)**2) * a) % p else: return (square_and_multiply(a, n // 2, p)**2) % p return (square_and_multiply(a, (p - 1) // 2, p) % p) == 1
def is_quad_residue(a, p): """ returns True if a is a quadratic residue of p p should be a prime and a should be relatively prime to p """ if not isprime(p) or p == 2: raise ValueError("p should be an odd prime") if igcd(a, p) != 1: raise ValueError("The two numbers should be relatively prime") if a > p: a = a % p def square_and_multiply(a, n, p): if n == 0: return 1 elif n == 1: return a elif n % 2 == 1: return ((square_and_multiply(a, n // 2, p) ** 2) * a) % p else: return (square_and_multiply(a, n // 2, p) ** 2) % p return (square_and_multiply(a, (p - 1) // 2, p) % p) == 1
def is_quad_residue(a, p): """ Returns True if ``a`` (mod ``p``) is in the set of squares mod ``p``, i.e a % p in set([i**2 % p for i in range(p)]). If ``p`` is an odd prime, an iterative method is used to make the determination. >>> from sympy.ntheory import is_quad_residue >>> list(set([i**2 % 7 for i in range(7)])) [0, 1, 2, 4] >>> [j for j in range(7) if is_quad_residue(j, 7)] [0, 1, 2, 4] """ a, p = int_tested(a, p) if p < 1: raise ValueError('p must be > 0') if a >= p or a < 0: a = a % p if a < 2 or p < 3: return True if not isprime(p): if p % 2 and jacobi_symbol(a, p) == -1: return False for i in range(2, p//2 + 1): if i**2 % p == a: return True return False def square_and_multiply(a, n, p): if n == 1: return a elif n % 2 == 1: return ((square_and_multiply(a, n // 2, p) ** 2) * a) % p else: return (square_and_multiply(a, n // 2, p) ** 2) % p return (square_and_multiply(a, (p - 1) // 2, p) % p) == 1
def _check_termination(factors, n, verbose=False): """ Helper function for integer factorization. Checks if ``n`` is a prime or a perfect power, and in those cases updates the factorization and raises ``StopIteration``. """ if verbose: print "Checking if remaining factor terminates the factorization" n = int(n) if n == 1: raise StopIteration p = perfect_power(n) if p: base, exp = p if verbose: print "-- Remaining factor is a perfect power: %i ** %i" % (base, exp) for b, e in factorint(base).iteritems(): factors[b] = exp*e raise StopIteration if isprime(n): if verbose: print "Remaining factor", n, "is prime" factors[n] = 1 raise StopIteration
def factorint(n, limit=None, use_trial=True, use_rho=True, use_pm1=True, verbose=False, visual=None): r""" Given a positive integer ``n``, ``factorint(n)`` returns a dict containing the prime factors of ``n`` as keys and their respective multiplicities as values. For example: >>> from sympy.ntheory import factorint >>> factorint(2000) # 2000 = (2**4) * (5**3) {2: 4, 5: 3} >>> factorint(65537) # This number is prime {65537: 1} For input less than 2, factorint behaves as follows: - ``factorint(1)`` returns the empty factorization, ``{}`` - ``factorint(0)`` returns ``{0:1}`` - ``factorint(-n)`` adds ``-1:1`` to the factors and then factors ``n`` Partial Factorization: If ``limit`` (> 3) is specified, the search is stopped after performing trial division up to (and including) the limit (or taking a corresponding number of rho/p-1 steps). This is useful if one has a large number and only is interested in finding small factors (if any). Note that setting a limit does not prevent larger factors from being found early; it simply means that the largest factor may be composite. Since checking for perfect power is relatively cheap, it is done regardless of the limit setting. This number, for example, has two small factors and a huge semi-prime factor that cannot be reduced easily: >>> from sympy.ntheory import isprime >>> a = 1407633717262338957430697921446883 >>> f = factorint(a, limit=10000) >>> f == {991: 1, 202916782076162456022877024859L: 1, 7: 1} True >>> isprime(max(f)) False This number has a small factor and a residual perfect power whose base is greater than the limit: >>> factorint(3*101**7, limit=5) {3: 1, 101: 7} Visual Factorization: If ``visual`` is set to ``True``, then it will return a visual factorization of the integer. For example: >>> from sympy import pprint >>> pprint(factorint(4200, visual=True)) 3 1 2 1 2 *3 *5 *7 Note that this is achieved by using the evaluate=False flag in Mul and Pow. If you do other manipulations with an expression where evaluate=False, it may evaluate. Therefore, you should use the visual option only for visualization, and use the normal dictionary returned by visual=False if you want to perform operations on the factors. You can easily switch between the two forms by sending them back to factorint: >>> from sympy import Mul, Pow >>> regular = factorint(1764); regular {2: 2, 3: 2, 7: 2} >>> pprint(factorint(regular)) 2 2 2 2 *3 *7 >>> visual = factorint(1764, visual=True); pprint(visual) 2 2 2 2 *3 *7 >>> print factorint(visual) {2: 2, 3: 2, 7: 2} If you want to send a number to be factored in a partially factored form you can do so with a dictionary or unevaluated expression: >>> factorint(factorint({4: 2, 12: 3})) # twice to toggle to dict form {2: 10, 3: 3} >>> factorint(Mul(4, 12, evaluate=False)) {2: 4, 3: 1} The table of the output logic is: ====== ====== ======= ======= Visual ------ ---------------------- Input True False other ====== ====== ======= ======= dict mul dict mul n mul dict dict mul mul dict dict ====== ====== ======= ======= Notes ===== Algorithm: The function switches between multiple algorithms. Trial division quickly finds small factors (of the order 1-5 digits), and finds all large factors if given enough time. The Pollard rho and p-1 algorithms are used to find large factors ahead of time; they will often find factors of the order of 10 digits within a few seconds: >>> factors = factorint(12345678910111213141516) >>> for base, exp in sorted(factors.items()): ... print base, exp ... 2 2 2507191691 1 1231026625769 1 Any of these methods can optionally be disabled with the following boolean parameters: - ``use_trial``: Toggle use of trial division - ``use_rho``: Toggle use of Pollard's rho method - ``use_pm1``: Toggle use of Pollard's p-1 method ``factorint`` also periodically checks if the remaining part is a prime number or a perfect power, and in those cases stops. If ``verbose`` is set to ``True``, detailed progress is printed. See Also ======== smoothness, smoothness_p, divisors """ factordict = {} if visual and not isinstance(n, Mul) and not isinstance(n, dict): factordict = factorint(n, limit=limit, use_trial=use_trial, use_rho=use_rho, use_pm1=use_pm1, verbose=verbose, visual=False) elif isinstance(n, Mul): factordict = dict([(int(k), int(v)) for k, v in n.as_powers_dict().items()]) elif isinstance(n, dict): factordict = n if factordict and (isinstance(n, Mul) or isinstance(n, dict)): # check it for k in factordict.keys(): if isprime(k): continue e = factordict.pop(k) d = factorint(k, limit=limit, use_trial=use_trial, use_rho=use_rho, use_pm1=use_pm1, verbose=verbose, visual=False) for k, v in d.items(): if k in factordict: factordict[k] += v*e else: factordict[k] = v*e if visual or (type(n) is dict and visual is not True and visual is not False): if factordict == {}: return S.One if -1 in factordict: factordict.pop(-1) args = [S.NegativeOne] else: args = [] args.extend([Pow(*i, evaluate=False) for i in sorted(factordict.items())]) return Mul(*args, evaluate=False) elif isinstance(n, dict) or isinstance(n, Mul): return factordict assert use_trial or use_rho or use_pm1 n = as_int(n) if limit: limit = int(limit) # special cases if n < 0: factors = factorint( -n, limit=limit, use_trial=use_trial, use_rho=use_rho, use_pm1=use_pm1, verbose=verbose, visual=False) factors[-1] = 1 return factors if limit: if limit < 2: if n == 1: return {} return {n: 1} elif n < 10: # doing this we are assured of getting a limit > 2 # when we have to compute it later return [{0: 1}, {}, {2: 1}, {3: 1}, {2: 2}, {5: 1}, {2: 1, 3: 1}, {7: 1}, {2: 3}, {3: 2}][n] factors = {} # do simplistic factorization if verbose: sn = str(n) if len(sn) > 50: print 'Factoring %s' % sn[:5] + \ '..(%i other digits)..' % (len(sn) - 10) + sn[-5:] else: print 'Factoring', n if use_trial: # this is the preliminary factorization for small factors small = 2**15 fail_max = 600 small = min(small, limit or small) if verbose: print trial_int_msg % (2, small, fail_max) n, next_p = _factorint_small(factors, n, small, fail_max) else: next_p = 2 if factors and verbose: for k in sorted(factors): print factor_msg % (k, factors[k]) if next_p == 0: if n > 1: factors[int(n)] = 1 if verbose: print complete_msg return factors # continue with more advanced factorization methods # first check if the simplistic run didn't finish # because of the limit and check for a perfect # power before exiting try: if limit and next_p > limit: if verbose: print 'Exceeded limit:', limit _check_termination(factors, n, limit, use_trial, use_rho, use_pm1, verbose) if n > 1: factors[int(n)] = 1 return factors else: # Before quitting (or continuing on)... # ...do a Fermat test since it's so easy and we need the # square root anyway. Finding 2 factors is easy if they are # "close enough." This is the big root equivalent of dividing by # 2, 3, 5. sqrt_n = integer_nthroot(n, 2)[0] a = sqrt_n + 1 a2 = a**2 b2 = a2 - n for i in range(3): b, fermat = integer_nthroot(b2, 2) if fermat: break b2 += 2*a + 1 # equiv to (a+1)**2 - n a += 1 if fermat: if verbose: print fermat_msg if limit: limit -= 1 for r in [a - b, a + b]: facs = factorint(r, limit=limit, use_trial=use_trial, use_rho=use_rho, use_pm1=use_pm1, verbose=verbose) factors.update(facs) raise StopIteration # ...see if factorization can be terminated _check_termination(factors, n, limit, use_trial, use_rho, use_pm1, verbose) except StopIteration: if verbose: print complete_msg return factors # these are the limits for trial division which will # be attempted in parallel with pollard methods low, high = next_p, 2*next_p limit = limit or sqrt_n # add 1 to make sure limit is reached in primerange calls limit += 1 while 1: try: high_ = high if limit < high_: high_ = limit # Trial division if use_trial: if verbose: print trial_msg % (low, high_) ps = sieve.primerange(low, high_) n, found_trial = _trial(factors, n, ps, verbose) if found_trial: _check_termination(factors, n, limit, use_trial, use_rho, use_pm1, verbose) else: found_trial = False if high > limit: if verbose: print 'Exceeded limit:', limit if n > 1: factors[int(n)] = 1 raise StopIteration # Only used advanced methods when no small factors were found if not found_trial: if (use_pm1 or use_rho): high_root = max(int(math.log(high_**0.7)), low, 3) # Pollard p-1 if use_pm1: if verbose: print (pm1_msg % (high_root, high_)) c = pollard_pm1(n, B=high_root, seed=high_) if c: # factor it and let _trial do the update ps = factorint(c, limit=limit - 1, use_trial=use_trial, use_rho=use_rho, use_pm1=use_pm1, verbose=verbose) n, _ = _trial(factors, n, ps, verbose=False) _check_termination(factors, n, limit, use_trial, use_rho, use_pm1, verbose) # Pollard rho if use_rho: max_steps = high_root if verbose: print (rho_msg % (1, max_steps, high_)) c = pollard_rho(n, retries=1, max_steps=max_steps, seed=high_) if c: # factor it and let _trial do the update ps = factorint(c, limit=limit - 1, use_trial=use_trial, use_rho=use_rho, use_pm1=use_pm1, verbose=verbose) n, _ = _trial(factors, n, ps, verbose=False) _check_termination(factors, n, limit, use_trial, use_rho, use_pm1, verbose) except StopIteration: if verbose: print complete_msg return factors low, high = high, high*2
import primetest print primetest.isprime(2) def quadratic(n, a, b): return n**2+a*n+b count = 0 ans = 0 for a in xrange(-1000,1001): for b in xrange(-1000,1001): n = 0 while primetest.isprime(quadratic(n,a,b)): n+=1 if count < n: count = n ans = a*b print {a,b} print ans
def factorint(n, limit=None, verbose=False): """ Given a positive integer n, factorint(n) returns a list [(p_1, m_1), (p_2, m_2), ...] with all p prime and n = p_1**m_1 * p_2**m_2 * ... Special cases: 1 factors as [], 0 factors as [(0, 1)], and negative integers factor as [(-1, 1), ...]. The function uses a composite algorithm, switching between Pollard's p-1 method and looking for small factors through trial division. It is sometimes useful to look only for small factors. If 'limit' is specified, factorint will only perform trial division with candidate factors up to this limit (and p-1 search up to the same smoothness bound). As a result, the last 'prime' in the returned list may be composite. Example usage ============= Here are some simple factorizations (with at most six digits in the second largest factor). They should all complete within a fraction of a second: >>> factorint(1) [] >>> factorint(100) [(2, 2), (5, 2)] >>> factorint(17*19) [(17, 1), (19, 1)] >>> factorint(prime(100)*prime(1000)*prime(10000)) [(541, 1), (7919, 1), (104729, 1)] >>> factors = factorint(2**(2**6) + 1) >>> for base, exp in factors: print base, exp ... 274177 1 67280421310721 1 Factors on the order of 10 digits can generally be found quickly. The following computations should complete within a few seconds: >>> factors = factorint(21477639576571) >>> for base, exp in factors: print base, exp ... 4410317 1 4869863 1 >>> factors = factorint(12345678910111213141516) >>> for base, exp in factors: print base, exp ... 2 2 2507191691 1 1231026625769 1 >>> factors = factorint(5715365922033905625269) >>> for base, exp in factors: print base, exp ... 74358036521 1 76862786989 1 This number has an enormous semiprime factor that is better ignored: >>> a = 1407633717262338957430697921446883 >>> factorint(a, limit=10000) [(7, 1), (991, 1), (202916782076162456022877024859, 1)] >>> isprime(_[-1][0]) False """ n = int(n) if n < 0: return [(-1, 1)] + factorint(-n, limit) if n == 0: return [(0, 1)] if n == 1: return [] if isprime(n): return [(n, 1)] if limit is None: limit = int(n**0.5) + 1 factors = [] low, high = 2, 50 while 1: # Trial divide for small factors first tfactors = trial(n, sieve.primerange(low, min(high, limit))) if verbose: print "trial division from", low, "to", \ min(high,limit)-1, "gave", tfactors # If all were primes, we're done if isprime(tfactors[-1][0]): factors += tfactors break elif tfactors[-1][0] == 1: factors += tfactors[:-1] break else: factors += tfactors[:-1] n = tfactors[-1][0] # If we're lucky, Pollard's p-1 will extract a large factor w = pollard_pm1(n, high) if verbose: print "pollard p-1 with smoothness bound", high, "gave", w print if w is not None: # w may be composite for f, m in factorint(w, limit): m *= multiplicity(f, n) factors += [(f, m)] n //= f**(m) if n == 1: break if isprime(n): factors += [(int(n), 1)] break if high > limit: factors += [(int(n), 1)] break low, high = high, high * 5 return sorted(factors)
def factorint(n, limit=None, verbose=False): """ Given a positive integer n, factorint(n) returns a list [(p_1, m_1), (p_2, m_2), ...] with all p prime and n = p_1**m_1 * p_2**m_2 * ... Special cases: 1 factors as [], 0 factors as [(0, 1)], and negative integers factor as [(-1, 1), ...]. The function uses a composite algorithm, switching between Pollard's p-1 method and looking for small factors through trial division. It is sometimes useful to look only for small factors. If 'limit' is specified, factorint will only perform trial division with candidate factors up to this limit (and p-1 search up to the same smoothness bound). As a result, the last 'prime' in the returned list may be composite. Example usage ============= Here are some simple factorizations (with at most six digits in the second largest factor). They should all complete within a fraction of a second: >>> factorint(1) [] >>> factorint(100) [(2, 2), (5, 2)] >>> factorint(17*19) [(17, 1), (19, 1)] >>> factorint(prime(100)*prime(1000)*prime(10000)) [(541, 1), (7919, 1), (104729, 1)] >>> factors = factorint(2**(2**6) + 1) >>> for base, exp in factors: print base, exp ... 274177 1 67280421310721 1 Factors on the order of 10 digits can generally be found quickly. The following computations should complete within a few seconds: >>> factors = factorint(21477639576571) >>> for base, exp in factors: print base, exp ... 4410317 1 4869863 1 >>> factors = factorint(12345678910111213141516) >>> for base, exp in factors: print base, exp ... 2 2 2507191691 1 1231026625769 1 >>> factors = factorint(5715365922033905625269) >>> for base, exp in factors: print base, exp ... 74358036521 1 76862786989 1 This number has an enormous semiprime factor that is better ignored: >>> a = 1407633717262338957430697921446883 >>> factorint(a, limit=10000) [(7, 1), (991, 1), (202916782076162456022877024859L, 1)] >>> isprime(_[-1][0]) False """ n = int(n) if n < 0: return [(-1, 1)] + factorint(-n, limit) if n == 0: return [(0, 1)] if n == 1: return [] if isprime(n): return [(n, 1)] if limit is None: limit = int(n**0.5) + 1 factors = [] low, high = 2, 50 while 1: # Trial divide for small factors first tfactors = trial(n, sieve.primerange(low, min(high, limit))) if verbose: print "trial division from", low, "to", \ min(high,limit)-1, "gave", tfactors # If all were primes, we're done if isprime(tfactors[-1][0]): factors += tfactors break elif tfactors[-1][0] == 1: factors += tfactors[:-1] break else: factors += tfactors[:-1] n = tfactors[-1][0] # If we're lucky, Pollard's p-1 will extract a large factor w = pollard_pm1(n, high) if verbose: print "pollard p-1 with smoothness bound", high, "gave", w print if w is not None: # w may be composite for f, m in factorint(w, limit): m *= multiplicity(f, n) factors += [(f, m)] n //= f**(m) if n == 1: break if isprime(n): factors += [(int(n), 1)] break if high > limit: factors += [(int(n), 1)] break low, high = high, high*5 return sorted(factors)
def factorint(n, limit=None, use_trial=True, use_rho=True, use_pm1=True, verbose=False, visual=None): r""" Given a positive integer ``n``, ``factorint(n)`` returns a dict containing the prime factors of ``n`` as keys and their respective multiplicities as values. For example: >>> from sympy.ntheory import factorint >>> factorint(2000) # 2000 = (2**4) * (5**3) {2: 4, 5: 3} >>> factorint(65537) # This number is prime {65537: 1} For input less than 2, factorint behaves as follows: - ``factorint(1)`` returns the empty factorization, ``{}`` - ``factorint(0)`` returns ``{0:1}`` - ``factorint(-n)`` adds ``-1:1`` to the factors and then factors ``n`` Partial Factorization: If ``limit`` (> 3) is specified, the search is stopped after performing trial division up to (and including) the limit (or taking a corresponding number of rho/p-1 steps). This is useful if one has a large number and only is interested in finding small factors (if any). Note that setting a limit does not prevent larger factors from being found early; it simply means that the largest factor may be composite. Since checking for perfect power is relatively cheap, it is done regardless of the limit setting. This number, for example, has two small factors and a huge semi-prime factor that cannot be reduced easily: >>> from sympy.ntheory import isprime >>> a = 1407633717262338957430697921446883 >>> f = factorint(a, limit=10000) >>> f == {991: 1, 202916782076162456022877024859L: 1, 7: 1} True >>> isprime(max(f)) False This number has a small factor and a residual perfect power whose base is greater than the limit: >>> factorint(3*101**7, limit=5) {3: 1, 101: 7} Visual Factorization: If ``visual`` is set to ``True``, then it will return a visual factorization of the integer. For example: >>> from sympy import pprint >>> pprint(factorint(4200, visual=True)) 3 1 2 1 2 *3 *5 *7 Note that this is achieved by using the evaluate=False flag in Mul and Pow. If you do other manipulations with an expression where evaluate=False, it may evaluate. Therefore, you should use the visual option only for visualization, and use the normal dictionary returned by visual=False if you want to perform operations on the factors. You can easily switch between the two forms by sending them back to factorint: >>> from sympy import Mul, Pow >>> regular = factorint(1764); regular {2: 2, 3: 2, 7: 2} >>> pprint(factorint(regular)) 2 2 2 2 *3 *7 >>> visual = factorint(1764, visual=True); pprint(visual) 2 2 2 2 *3 *7 >>> print factorint(visual) {2: 2, 3: 2, 7: 2} If you want to send a number to be factored in a partially factored form you can do so with a dictionary or unevaluated expression: >>> factorint(factorint({4: 2, 12: 3})) # twice to toggle to dict form {2: 10, 3: 3} >>> factorint(Mul(4, 12, **dict(evaluate=False))) {2: 4, 3: 1} The table of the output logic is: ====== ====== ======= ======= Visual ------ ---------------------- Input True False other ====== ====== ======= ======= dict mul dict mul n mul dict dict mul mul dict dict ====== ====== ======= ======= Notes ===== Algorithm: The function switches between multiple algorithms. Trial division quickly finds small factors (of the order 1-5 digits), and finds all large factors if given enough time. The Pollard rho and p-1 algorithms are used to find large factors ahead of time; they will often find factors of the order of 10 digits within a few seconds: >>> factors = factorint(12345678910111213141516) >>> for base, exp in sorted(factors.items()): ... print base, exp ... 2 2 2507191691 1 1231026625769 1 Any of these methods can optionally be disabled with the following boolean parameters: - ``use_trial``: Toggle use of trial division - ``use_rho``: Toggle use of Pollard's rho method - ``use_pm1``: Toggle use of Pollard's p-1 method ``factorint`` also periodically checks if the remaining part is a prime number or a perfect power, and in those cases stops. If ``verbose`` is set to ``True``, detailed progress is printed. See Also ======== smoothness, smoothness_p, divisors """ factordict = {} if visual and not isinstance(n, Mul) and not isinstance(n, dict): factordict = factorint(n, limit=limit, use_trial=use_trial, use_rho=use_rho, use_pm1=use_pm1, verbose=verbose, visual=False) elif isinstance(n, Mul): factordict = dict([(int(k), int(v)) for k, v in n.as_powers_dict().items()]) elif isinstance(n, dict): factordict = n if factordict and (isinstance(n, Mul) or isinstance(n, dict)): # check it for k in factordict.keys(): if isprime(k): continue e = factordict.pop(k) d = factorint(k, limit=limit, use_trial=use_trial, use_rho=use_rho, use_pm1=use_pm1, verbose=verbose, visual=False) for k, v in d.items(): if k in factordict: factordict[k] += v*e else: factordict[k] = v*e if visual or (type(n) is dict and visual is not True and visual is not False): if factordict == {}: return S.One if -1 in factordict: factordict.pop(-1) args = [S.NegativeOne] else: args = [] args.extend([Pow(*i, **{'evaluate':False}) for i in sorted(factordict.items())]) return Mul(*args, **{'evaluate': False}) elif isinstance(n, dict) or isinstance(n, Mul): return factordict assert use_trial or use_rho or use_pm1 n = as_int(n) if limit: limit = int(limit) # special cases if n < 0: factors = factorint( -n, limit=limit, use_trial=use_trial, use_rho=use_rho, use_pm1=use_pm1, verbose=verbose, visual=False) factors[-1] = 1 return factors if limit: if limit < 2: if n == 1: return {} return {n: 1} elif n < 10: # doing this we are assured of getting a limit > 2 # when we have to compute it later return [{0: 1}, {}, {2: 1}, {3: 1}, {2: 2}, {5: 1}, {2: 1, 3: 1}, {7: 1}, {2: 3}, {3: 2}][n] factors = {} # do simplistic factorization if verbose: sn = str(n) if len(sn) > 50: print 'Factoring %s' % sn[:5] + \ '..(%i other digits)..' % (len(sn) - 10) + sn[-5:] else: print 'Factoring', n if use_trial: # this is the preliminary factorization for small factors small = 2**15 fail_max = 600 small = min(small, limit or small) if verbose: print trial_int_msg % (2, small, fail_max) n, next_p = _factorint_small(factors, n, small, fail_max) else: next_p = 2 if factors and verbose: for k in sorted(factors): print factor_msg % (k, factors[k]) if next_p == 0: if n > 1: factors[int(n)] = 1 if verbose: print complete_msg return factors # continue with more advanced factorization methods # first check if the simplistic run didn't finish # because of the limit and check for a perfect # power before exiting try: if limit and next_p > limit: if verbose: print 'Exceeded limit:', limit _check_termination(factors, n, limit, use_trial, use_rho, use_pm1, verbose) if n > 1: factors[int(n)] = 1 return factors else: # Before quitting (or continuing on)... # ...do a Fermat test since it's so easy and we need the # square root anyway. Finding 2 factors is easy if they are # "close enough." This is the big root equivalent of dividing by # 2, 3, 5. sqrt_n = integer_nthroot(n, 2)[0] a = sqrt_n + 1 a2 = a**2 b2 = a2 - n for i in range(3): b, fermat = integer_nthroot(b2, 2) if fermat: break b2 += 2*a + 1 # equiv to (a+1)**2 - n a += 1 if fermat: if verbose: print fermat_msg if limit: limit -= 1 for r in [a - b, a + b]: facs = factorint(r, limit=limit, use_trial=use_trial, use_rho=use_rho, use_pm1=use_pm1, verbose=verbose) factors.update(facs) raise StopIteration # ...see if factorization can be terminated _check_termination(factors, n, limit, use_trial, use_rho, use_pm1, verbose) except StopIteration: if verbose: print complete_msg return factors # these are the limits for trial division which will # be attempted in parallel with pollard methods low, high = next_p, 2*next_p limit = limit or sqrt_n # add 1 to make sure limit is reached in primerange calls limit += 1 while 1: try: high_ = high if limit < high_: high_ = limit # Trial division if use_trial: if verbose: print trial_msg % (low, high_) ps = sieve.primerange(low, high_) n, found_trial = _trial(factors, n, ps, verbose) if found_trial: _check_termination(factors, n, limit, use_trial, use_rho, use_pm1, verbose) else: found_trial = False if high > limit: if verbose: print 'Exceeded limit:', limit if n > 1: factors[int(n)] = 1 raise StopIteration # Only used advanced methods when no small factors were found if not found_trial: if (use_pm1 or use_rho): high_root = max(int(math.log(high_**0.7)), low, 3) # Pollard p-1 if use_pm1: if verbose: print (pm1_msg % (high_root, high_)) c = pollard_pm1(n, B=high_root, seed=high_) if c: # factor it and let _trial do the update ps = factorint(c, limit=limit - 1, use_trial=use_trial, use_rho=use_rho, use_pm1=use_pm1, verbose=verbose) n, _ = _trial(factors, n, ps, verbose=False) _check_termination(factors, n, limit, use_trial, use_rho, use_pm1, verbose) # Pollard rho if use_rho: max_steps = high_root if verbose: print (rho_msg % (1, max_steps, high_)) c = pollard_rho(n, retries=1, max_steps=max_steps, seed=high_) if c: # factor it and let _trial do the update ps = factorint(c, limit=limit - 1, use_trial=use_trial, use_rho=use_rho, use_pm1=use_pm1, verbose=verbose) n, _ = _trial(factors, n, ps, verbose=False) _check_termination(factors, n, limit, use_trial, use_rho, use_pm1, verbose) except StopIteration: if verbose: print complete_msg return factors low, high = high, high*2
def ID46(maxn): primelist = [i for i in range(1, maxn + 1) if isprime(i)] i = 9 while True: if isprime(i): pass
from primetest import isprime print isprime(715827883)