# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# “Software”), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sub-license, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Modifications:
1.Once the nth digit and desired number of digits is selected, the
number of digits of working precision is calculated to ensure that
the hexadecimal digits returned are accurate. This is calculated as
This was checked by the following code which completed without
errors (and dig are the digits included in the test_bbp.py file):
for i in range(0,1000):
for j in range(1,1000):
a, b = pi_hex_digits(i, j), dig[i:i+j]
if a != b:
print(‘%s
%s’%(a,b))
Deceasing the additional digits by 1 generated errors, so ‘3’ is
the smallest additional precision needed to calculate the above
loop without errors. The following trailing 10 digits were also
checked to be accurate (and the times were slightly faster with
some of the constant modifications that were made):
Returns a string containing prec (default 14) digits
starting at the nth digit of pi in hex. Counting of digits
starts at 0 and the decimal is not counted, so for n = 0 the
returned value starts with 3; n = 1 corresponds to the first
digit past the decimal point (which in hex is 2).
Return an iterator over the convergents of a continued fraction (cf).
The parameter should be an iterable returning successive
partial quotients of the continued fraction, such as might be
returned by continued_fraction_iterator. In computing the
convergents, the continued fraction need not be strictly in
canonical form (all integers, all but the first positive).
Rational and negative elements may be present in the expansion.
modelparameters.sympy.ntheory.continued_fraction.continued_fraction_periodic(p, q, d=0)[source]¶
Find the periodic continued fraction expansion of a quadratic irrational.
Compute the continued fraction expansion of a rational or a
quadratic irrational number, i.e. frac{p + sqrt{d}}{q}, where
p, q and d ge 0 are integers.
Returns the continued fraction representation (canonical form) as
a list of integers, optionally ending (for quadratic irrationals)
with repeating block as the last term of this list.
Parameters:
p (int) – the rational part of the number’s numerator
Reduce a continued fraction to a rational or quadratic irrational.
Compute the rational or quadratic irrational number from its
terminating or periodic continued fraction expansion. The
continued fraction expansion (cf) should be supplied as a
terminating iterator supplying the terms of the expansion. For
terminating continued fractions, this is equivalent to
list(continued_fraction_convergents(cf))[-1], only a little more
efficient. If the expansion has a repeating part, a list of the
repeating terms should be returned as the last element from the
iterator. This is the format returned by
continued_fraction_periodic.
For quadratic irrationals, returns the largest solution found,
which is generally the one sought, if the fraction is in canonical
form (all terms positive except possibly the first).
Also called the Fibonacci-Sylvester algorithm [2]_.
At each step, extract the largest unit fraction less
than the target and replace the target with the remainder.
It has some distinct properties:
Given p/q in lowest terms, generates an expansion of maximum
length p. Even as the numerators get large, the number of
terms is seldom more than a handful.
Uses minimal memory.
The terms can blow up (standard examples of this are 5/121 and
31/311). The denominator is at most squared at each step
(doubly-exponential growth) and typically exhibits
singly-exponential growth.
Graham Jewett Algorithm
The algorithm suggested by the result of Graham and Jewett.
Note that this has a tendency to blow up: the length of the
resulting expansion is always 2**(x/gcd(x,y))-1. See [3].
Takenouchi Algorithm
The algorithm suggested by Takenouchi (1921).
Differs from the Graham-Jewett algorithm only in the handling
of duplicates. See [3].
Golomb’s Algorithm
A method given by Golumb (1962), using modular arithmetic and
inverses. It yields the same results as a method using continued
fractions proposed by Bleicher (1972). See [4].
If the given rational is greater than or equal to 1, a greedy algorithm
of summing the harmonic sequence 1/1 + 1/2 + 1/3 + … is used, taking
all the unit fractions of this sequence until adding one more would be
greater than the given number. This list of denominators is prefixed
to the result from the requested algorithm used on the remainder. For
example, if r is 8/3, using the Greedy algorithm, we get [1, 2, 3, 4,
5, 6, 7, 14, 420], where the beginning of the sequence, [1, 2, 3, 4, 5,
6, 7] is part of the harmonic sequence summing to 363/140, leaving a
remainder of 31/420, which yields [14, 420] by the Greedy algorithm.
The result of egyptian_fraction(Rational(8, 3), “Golomb”) is [1, 2, 3,
4, 5, 6, 7, 14, 574, 2788, 6460, 11590, 33062, 113820], and so on.
Returns a canonical form of cls applied to arguments args.
The eval() method is called when the class cls is about to be
instantiated and it should return either some simplified instance
(possible of some other class), or if the class cls should be
unmodified, return None.
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).
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..ntheoryimportfactorint>>> 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:
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:
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:
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:
Return (b,e) such that n == b**e if n is a
perfect power; otherwise return False.
By default, the base is recursively decomposed and the exponents
collected so the largest possible e is sought. If big=False
then the smallest possible e (thus prime) will be chosen.
If candidates for exponents are given, they are assumed to be sorted
and the first one that is larger than the computed maximum will signal
failure for the routine.
If factor=True then simultaneous factorization of n is attempted
since finding a factor indicates the only possible root for n. This
is True by default since only a few small factors will be tested in
the course of searching for the perfect power.
Use Pollard’s p-1 method to try to extract a nontrivial factor
of n. Either a divisor (perhaps composite) or None is returned.
The value of a is the base that is used in the test gcd(a**M - 1, n).
The default is 2. If retries > 0 then if no factor is found after the
first attempt, a new a will be generated randomly (using the seed)
and the process repeated.
Note: the value of M is lcm(1..B) = reduce(ilcm, range(2, B + 1)).
A search is made for factors next to even numbers having a power smoothness
less than B. Choosing a larger B increases the likelihood of finding a
larger factor but takes longer. Whether a factor of n is found or not
depends on a and the power smoothness of the even mumber just less than
the factor p (hence the name p - 1).
Although some discussion of what constitutes a good a some
descriptions are hard to interpret. At the modular.math site referenced
below it is stated that if gcd(a**M - 1, n) = N then a**M % q**r is 1
for every prime power divisor of N. But consider the following:
The B value has to do with the factors of the number next to the divisor,
not the divisors themselves. A worst case scenario is that the number next
to the factor p has a large prime divisisor or is a perfect power. If these
conditions apply then the power-smoothness will be about p/2 or p. The more
realistic is that there will be a large prime factor next to p requiring
a B value on the order of p/2. Although primes may have been searched for
up to this level, the p/2 is a factor of p - 1, something that we don’t
know. The modular.math reference below states that 15% of numbers in the
range of 10**15 to 15**15 + 10**4 are 10**6 power smooth so a B of 10**6
will fail 85% of the time in that range. From 10**8 to 10**8 + 10**3 the
percentages are nearly reversed…but in that range the simple trial
division is quite fast.
References
Richard Crandall & Carl Pomerance (2005), “Prime Numbers:
A Computational Perspective”, Springer, 2nd edition, 236-238
Use Pollard’s rho method to try to extract a nontrivial factor
of n. The returned factor may be a composite number. If no
factor is found, None is returned.
The algorithm generates pseudo-random values of x with a generator
function, replacing x with F(x). If F is not supplied then the
function x**2 + a is used. The first value supplied to F(x) is s.
Upon failure (if retries is > 0) a new a and s will be
supplied; the a will be ignored if F was supplied.
The sequence of numbers generated by such functions generally have a
a lead-up to some number and then loop around back to that number and
begin to repeat the sequence, e.g. 1, 2, 3, 4, 5, 3, 4, 5 – this leader
and loop look a bit like the Greek letter rho, and thus the name, ‘rho’.
For a given function, very different leader-loop values can be obtained
so it is a good idea to allow for retries:
Instead of checking the differences of all generated values for a gcd
with n, only the kth and 2*kth numbers are checked, e.g. 1st and 2nd,
2nd and 4th, 3rd and 6th until it has been detected that the loop has been
traversed. Loops may be many thousands of steps long before rho finds a
factor or reports failure. If max_steps is specified, the iteration
is cancelled with a failure after the specified number of steps.
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.
Returns a canonical form of cls applied to arguments args.
The eval() method is called when the class cls is about to be
instantiated and it should return either some simplified instance
(possible of some other class), or if the class cls should be
unmodified, return None.
Returns a canonical form of cls applied to arguments args.
The eval() method is called when the class cls is about to be
instantiated and it should return either some simplified instance
(possible of some other class), or if the class cls should be
unmodified, return None.
Returns a canonical form of cls applied to arguments args.
The eval() method is called when the class cls is about to be
instantiated and it should return either some simplified instance
(possible of some other class), or if the class cls should be
unmodified, return None.
Return a list of [m, (p, (M, sm(p + m), psm(p + m)))…]
where:
p**M is the base-p divisor of n
sm(p + m) is the smoothness of p + m (m = -1 by default)
psm(p + m) is the power smoothness of p + m
The list is sorted according to smoothness (default) or by power smoothness
if power=1.
The smoothness of the numbers to the left (m = -1) or right (m = 1) of a
factor govern the results that are obtained from the p +/- 1 type factoring
methods.
Returns a canonical form of cls applied to arguments args.
The eval() method is called when the class cls is about to be
instantiated and it should return either some simplified instance
(possible of some other class), or if the class cls should be
unmodified, return None.
Returns a canonical form of cls applied to arguments args.
The eval() method is called when the class cls is about to be
instantiated and it should return either some simplified instance
(possible of some other class), or if the class cls should be
unmodified, return None.
Return all unitary divisors of n sorted from 1..n by default.
If generator is True an unordered generator is returned.
The number of unitary divisors of n can be quite large if there are many
prime factors. If only the number of unitary divisors is desired use
udivisor_count(n).
An infinite list of prime numbers, implemented as a dynamically
growing sieve of Eratosthenes. When a lookup is requested involving
an odd number that has not been sieved, the sieve is automatically
extended up to that number.
Examples
>>> from..importsieve>>> sieve._reset()# this line for doctest only>>> 25insieveFalse>>> sieve._listarray('l', [2, 3, 5, 7, 11, 13, 17, 19, 23])
For a given iterated sequence, return a generator that gives
the length of the iterated cycle (lambda) and the length of terms
before the cycle begins (mu); if values is True then the
terms of the sequence will be returned instead. The sequence is
started with value x0.
Note: more than the first lambda + mu terms may be returned and this
is the cost of cycle detection with Brent’s method; there are, however,
generally less terms calculated than would have been calculated if the
proper ending point were determined, e.g. by using Floyd’s method.
>>> from.generateimportcycle_length
This will yield successive values of i <– func(i):
Return the nth prime, with the primes indexed as prime(1) = 2,
prime(2) = 3, etc…. The nth prime is approximately n*log(n).
Logarithmic integral of x is a pretty nice approximation for number of
primes <= x, i.e.
li(x) ~ pi(x)
In fact, for the numbers we are concerned about( x<1e11 ),
li(x) - pi(x) < 50000
Also,
li(x) > pi(x) can be safely assumed for the numbers which
can be evaluated by this function.
Here, we find the least integer m such that li(m) > n using binary search.
Now pi(m-1) < li(m-1) <= n,
We find pi(m - 1) using primepi function.
Starting from m, we have to find n - pi(m-1) more primes.
For the inputs this implementation can handle, we will have to test
primality for at max about 10**5 numbers, to get our answer.
Return the value of the prime counting function pi(n) = the number
of prime numbers less than or equal to n.
Algorithm Description:
In sieve method, we remove all multiples of prime p
except p itself.
Let phi(i,j) be the number of integers 2 <= k <= i
which remain after sieving from primes less than
or equal to j.
Clearly, pi(n) = phi(n, sqrt(n))
If j is not a prime,
phi(i,j) = phi(i, j - 1)
if j is a prime,
We remove all numbers(except j) whose
smallest prime factor is j.
Let x= j*a be such a number, where 2 <= a<= i / j
Now, after sieving from primes <= j - 1,
a must remain
(because x, and hence a has no prime factor <= j - 1)
Clearly, there are phi(i / j, j - 1) such a
which remain on sieving from primes <= j - 1
Now, if a is a prime less than equal to j - 1,
x= j*a has smallest prime factor = a, and
has already been removed(by sieving from a).
So, we don’t need to remove it again.
(Note: there will be pi(j - 1) such x)
Thus, number of x, that will be removed are:
phi(i / j, j - 1) - phi(j - 1, j - 1)
(Note that pi(j - 1) = phi(j - 1, j - 1))
So,following recursion is used and implemented as dp:
phi(a, b) = phi(a, b - 1), if b is not a prime
phi(a, b) = phi(a, b-1)-phi(a / b, b-1) + phi(b-1, b-1), if b is prime
Clearly a is always of the form floor(n / k),
which can take at most 2*sqrt(n) values.
Two arrays arr1,arr2 are maintained
arr1[i] = phi(i, j),
arr2[i] = phi(n // i, j)
Generate a list of all prime numbers in the range [a, b).
If the range exists in the default sieve, the values will
be returned from there; otherwise values will be returned
but will not modify the sieve.
Notes
Some famous conjectures about the occurence of primes in a given
range are [1]:
Twin primes: though often not, the following will give 2 primes
an infinite number of times:
primerange(6*n - 1, 6*n + 2)
Legendre’s: the following always yields at least one prime
primerange(n**2, (n+1)**2+1)
Bertrand’s (proven): there is always a prime in the range
primerange(n, 2*n)
Brocard’s: there are at least four primes in the range
primerange(prime(n)**2, prime(n+1)**2)
The average gap between primes is log(n) [2]; the gap between
primes can be arbitrarily large since sequences of composite
numbers are arbitrarily large, e.g. the numbers in the sequence
n! + 2, n! + 3 … n! + n are all composite.
The Sieve method, primerange, is generally faster but it will
occupy more memory as the sieve stores values. The default
instance of Sieve, named sieve, can be used:
Returns the product of the first n primes (default) or
the primes less than or equal to n (when nth=False).
>>> from.generateimportprimorial,randprime,primerange>>> from..importfactorint,Mul,primefactors,sqrt>>> primorial(4)# the first 4 primes are 2, 3, 5, 7210>>> primorial(4,nth=False)# primes <= 4 are 2 and 36>>> primorial(1)2>>> primorial(1,nth=False)1>>> primorial(sqrt(101),nth=False)210
One can argue that the primes are infinite since if you take
a set of primes and multiply them together (e.g. the primorial) and
then add or subtract 1, the result cannot be divided by any of the
original factors, hence either 1 or more new primes must divide this
product of primes.
In this case, the number itself is a new prime:
>>> factorint(primorial(4)+1){211: 1}
In this case two new primes are the factors:
>>> factorint(primorial(4)-1){11: 1, 19: 1}
Here, some primes smaller and larger than the primes multiplied together
are obtained:
The moduli in m are assumed to be pairwise coprime. The output
is then an integer f, such that f = v_i mod m_i for each pair out
of v and m. If symmetric is False a positive integer will be
returned, else |f| will be less than or equal to the LCM of the
moduli, and thus f may be negative.
If the moduli are not co-prime the correct result will be returned
if/when the test of the result is found to be incorrect. This result
will be None if there is no solution.
The keyword check can be set to False if it is known that the moduli
are coprime.
As an example consider a set of residues U=[49,76,65]
and a set of moduli M=[99,97,95]. Then we have:
Note: the order of gf_crt’s arguments is reversed relative to crt,
and that solve_congruence takes residue, modulus pairs.
Programmer’s note: rather than checking that all pairs of moduli share
no GCD (an O(n**2) test) and rather than factoring all moduli and seeing
that there is no factor in common, a check that the result gives the
indicated residuals is performed – an O(n) operation.
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.
The coefficients a(n,k) can be computed using the
J.C.P. Miller Pure Recurrence [see D.E.Knuth, Seminumerical
Algorithms, The art of Computer Programming v.2, Addison
Wesley, Reading, 1981;]:
a(n,k)=1/(kp_0)sum_{i=1}^mp_i((n+1)i-k)a(n,k-i),
where a(n,0)=p_0^n.
modelparameters.sympy.ntheory.multinomial.multinomial_coefficients_iterator(m, n, _tuple=<class'tuple'>)[source]¶
multinomial coefficient iterator
This routine has been optimized for m large with respect to n by taking
advantage of the fact that when the monomial tuples t are stripped of
zeros, their coefficient is the same as that of the monomial tuples from
multinomial_coefficients(n,n). Therefore, the latter coefficients are
precomputed to save memory and time.
Extra Strong Lucas compositeness test. Returns False if n is
definitely composite, and True if n is a “extra strong” Lucas probable
prime.
The parameters are selected using P = 3, Q = 1, then incrementing P until
(D|n) == -1. The test itself is as defined in Grantham 2000, from the
Mo and Jones preprint. The parameter selection and test are the same as
used in OEIS A217719, Perl’s Math::Prime::Util, and the Lucas pseudoprime
page on Wikipedia.
With these parameters, there are no counterexamples below 2^64 nor any
known above that range. It is 20-50% faster than the strong test.
Because of the different parameters selected, there is no relationship
between the strong Lucas pseudoprimes and extra strong Lucas pseudoprimes.
In particular, one is not a subset of the other.
Return True if n == a * a for some integer a, else False.
If n is suspected of not being a square then this is a
quick method of confirming that it is not.
Test if n is a prime number (True) or not (False). For n < 2^64 the
answer is definitive; larger n values have a small probability of actually
being pseudoprimes.
Negative numbers (e.g. -2) are not considered prime.
The first step is looking for trivial factors, which if found enables
a quick return. Next, if the sieve is large enough, use bisection search
on the sieve. For small numbers, a set of deterministic Miller-Rabin
tests are performed with bases that are known to have no counterexamples
in their range. Finally if the number is larger than 2^64, a strong
BPSW test is performed. While this is a probable prime test and we
believe counterexamples exist, there are no known counterexamples.
modelparameters.sympy.ntheory.residue_ntheory.discrete_log(n, a, b, order=None, prime_order=None)[source]¶
Compute the discrete logarithm of a to the base b modulo n.
This is a recursive function to reduce the discrete logarithm problem in
cyclic groups of composite order to the problem in cyclic groups of prime
order.
It employs different algorithms depending on the problem (subgroup order
size, prime order or not):
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:
For any integer m and any positive odd integer n the Jacobi symbol
is defined as the product of the Legendre symbols corresponding to the
prime factors of n:
\[\genfrac(){}{}{m}{n} =
\genfrac(){}{}{m}{p^{1}}^{\alpha_1}
\genfrac(){}{}{m}{p^{2}}^{\alpha_2}
...
\genfrac(){}{}{m}{p^{k}}^{\alpha_k}
\text{ where } n =
p_1^{\alpha_1}
p_2^{\alpha_2}
...
p_k^{\alpha_k}\]
Like the Legendre symbol, if the Jacobi symbol genfrac(){}{}{m}{n} = -1
then m is a quadratic nonresidue modulo n.
But, unlike the Legendre symbol, if the Jacobi symbol
genfrac(){}{}{m}{n} = 1 then m may or may not be a quadratic residue
modulo n.
For an integer a and an odd prime p, the Legendre symbol is
defined as
\[\begin{split}\genfrac(){}{}{a}{p} = \begin{cases}
0 & \text{if } p \text{ divides } a\\
1 & \text{if } a \text{ is a quadratic residue modulo } p\\
-1 & \text{if } a \text{ is a quadratic nonresidue modulo } p
\end{cases}\end{split}\]
(-1)^k if n is a square-free positive integer with k
number of prime factors.
It is an important multiplicative function in number theory
and combinatorics. It has applications in mathematical series,
algebraic number theory and also physics (Fermion operator has very
concrete realization with Möbius Function model).
Returns a canonical form of cls applied to arguments args.
The eval() method is called when the class cls is about to be
instantiated and it should return either some simplified instance
(possible of some other class), or if the class cls should be
unmodified, return None.
all_roots (if True the list of roots is returned or None) –
Notes
If there is no root it is returned None; else the returned root
is less or equal to p//2; in general is not the smallest one.
It is returned p//2 only if it is the only root.
Use all_roots only when it is expected that all the roots fit
in memory; otherwise use sqrt_mod_iter.