Integer and Number Theoretic Functions

Some integer functions.

The remainder on dividing 17 by 3:

Mod[17,3]

The integer part of 17/3:

Quotient[17,3]

(RefLink[Mod, paclet:ref/Mod]) also works with real numbers:

Mod[5.6,1.2]

The result from (RefLink[Mod, paclet:ref/Mod]) always has the same sign as the second argument:

Mod[-5.6,1.2]

For any integers a and b, it is always true that b*(RefLink[Quotient, paclet:ref/Quotient])[a,b]+(RefLink[Mod, paclet:ref/Mod])[a,b] is equal to a.

Integer remainders with offsets.

Particularly when you are using (RefLink[Mod, paclet:ref/Mod]) to get indices for parts of objects, you will often find it convenient to specify an offset.

This effectively extracts the 18(^th) part of the list, with the list treated cyclically:

Part[{a,b,c},Mod[18,3,1]]

The greatest common divisor function (RefLink[GCD, paclet:ref/GCD])[(Subscript[n, 1]),(Subscript[n, 2]),…] gives the largest integer that divides all the (Subscript[n, i]) exactly. When you enter a ratio of two integers, the Wolfram Language effectively uses (RefLink[GCD, paclet:ref/GCD]) to cancel out common factors and give a rational number in lowest terms.

The least common multiple function (RefLink[LCM, paclet:ref/LCM])[(Subscript[n, 1]),(Subscript[n, 2]),…] gives the smallest integer that contains all the factors of each of the (Subscript[n, i]).

The largest integer that divides both 24 and 15 is 3:

GCD[24,15]

The Kronecker delta function (RefLink[KroneckerDelta, paclet:ref/KroneckerDelta])[(Subscript[n, 1]),(Subscript[n, 2]),…] is equal to 1 if all the (Subscript[n, i]) are equal, and is 0 otherwise. (Subscript[δ, (Subscript[n, 1])(Subscript[n, 2])… ]) can be thought of as a totally symmetric tensor.

This gives a totally symmetric tensor of rank 3:

Array[KroneckerDelta,{3,3,3}]

Integer factoring and related functions.

This gives the factors of 24 as (2^3), (3^1). The first element in each list is the factor; the second is its exponent:

FactorInteger[24]

Here are the factors of a larger integer:

FactorInteger[111111111111111111]

You should realize that according to current mathematical thinking, integer factoring is a fundamentally difficult computational problem. As a result, you can easily type in an integer that the Wolfram Language will not be able to factor in anything short of an astronomical length of time. But as long as the integers you give are less than about 50 digits long, (RefLink[FactorInteger, paclet:ref/FactorInteger]) should have no trouble. And in special cases it will be able to deal with much longer integers.

Here is a rather special long integer:

30!

The Wolfram Language can easily factor this special integer:

FactorInteger[%]

Although the Wolfram Language may not be able to factor a large integer, it can often still test whether or not the integer is a prime. In addition, the Wolfram Language has a fast way of finding the k(^th) prime number.

It is often much faster to test whether a number is prime than to factor it:

PrimeQ[234242423]

Here is a plot of the first 100 primes:

ListPlot[Table[Prime[n],{n,100}]]

This is the millionth prime:

Prime[1000000]

Particularly in number theory, it is often more important to know the distribution of primes than their actual values. The function (RefLink[PrimePi, paclet:ref/PrimePi])[x] gives the number of primes π(x) that are less than or equal to x.

This gives the number of primes less than a billion:

PrimePi[10^9]

(RefLink[PrimeNu, paclet:ref/PrimeNu]) gives the number of distinct primes:

PrimeNu[10^9]

(RefLink[PrimeOmega, paclet:ref/PrimeOmega]) gives the number of prime factors counting multiplicities Ω(n) in n:

PrimeOmega[10^9]

Liouville's function gives (((-1))^k) where k is the number of prime factors counting multiplicity:

{LiouvilleLambda[3^5],LiouvilleLambda[2 3^5]}

The Mangoldt function returns the log of prime power base or zero when composite:

{MangoldtLambda[3^5],MangoldtLambda[2 3^5]}

By default, (RefLink[FactorInteger, paclet:ref/FactorInteger]) allows only real integers. But with the option setting (RefLink[GaussianIntegers, paclet:ref/GaussianIntegers])->(RefLink[True, paclet:ref/True]), it also handles Gaussian integers, which are complex numbers with integer real and imaginary parts. Just as it is possible to factor uniquely in terms of real primes, it is also possible to factor uniquely in terms of Gaussian primes. There is nevertheless some potential ambiguity in the choice of Gaussian primes. In the Wolfram Language, they are always chosen to have positive real parts, and non-negative imaginary parts, except for a possible initial factor of -1 or ±i.

Over the Gaussian integers, 2 can be factored as (-i)(((1+i))^2):

FactorInteger[2,GaussianIntegers->True]

Here are the factors of a Gaussian integer:

FactorInteger[111+78 I,GaussianIntegers->True]

Some functions from number theory.

The modular power function (RefLink[PowerMod, paclet:ref/PowerMod])[a,b,n] gives exactly the same results as (RefLink[Mod, paclet:ref/Mod])[a^b,n] for b>0. (RefLink[PowerMod, paclet:ref/PowerMod]) is much more efficient, however, because it avoids generating the full form of a^b.

You can use (RefLink[PowerMod, paclet:ref/PowerMod]) not only to find positive modular powers, but also to find modular inverses. For negative b, (RefLink[PowerMod, paclet:ref/PowerMod])[a,b,n] gives, if possible, an integer k such that k(a^(-b))≡1modn. (Whenever such an integer exists, it is guaranteed to be unique modulo n.) If no such integer k exists, the Wolfram Language leaves (RefLink[PowerMod, paclet:ref/PowerMod]) unevaluated.

(RefLink[PowerMod, paclet:ref/PowerMod]) is equivalent to using (RefLink[Power, paclet:ref/Power]), then (RefLink[Mod, paclet:ref/Mod]), but is much more efficient:

PowerMod[2,13451,3]

This gives the modular inverse of 3 modulo 7:

PowerMod[3,-1,7]

Multiplying the inverse by 3 modulo 7 gives 1, as expected:

Mod[3%,7]

This finds the smallest non-negative integer x so that (x^2) is equal to 3 mod 11:

PowerMod[3,1/2,11]

This verifies the result:

Mod[(5^2),11]

This returns all integers less than 11 which satisfy the relation:

PowerModList[3,1/2,11]

If d does not have a square root modulo n, (RefLink[PowerMod, paclet:ref/PowerMod])[d,n] will remain unevaluated and (RefLink[PowerModList, paclet:ref/PowerModList]) will return an empty list:

PowerMod[3,1/2,5]

PowerModList[3,1/2,5]

This checks that 3 is not a square modulo 5:

Mod[(({0,1,2,3,4})^2),5]

Even for a large modulus, the square root can be computed fairly quickly:

PowerMod[2,1/2,(10^64)+57]//Timing

(RefLink[PowerMod, paclet:ref/PowerMod])[d,n] also works for composite n:

PowerMod[3,1/2,(11^3)]

There are ϕ(k) distinct Dirichlet characters for a given modulus k, as labeled by the index j. Different conventions can give different orderings for the possible characters.

(RefLink[DirichletCharacter, paclet:ref/DirichletCharacter]) works for very large numbers:

DirichletCharacter[20!,300,23]

The Euler totient function ϕ(n) gives the number of integers less than n that are relatively prime to n. An important relation (Fermat's little theorem) is that (a^(ϕ(n)))≡1modn for all a relatively prime to n.

The Möbius function μ(n) is defined to be (((-1))^k) if n is a product of k distinct primes, and 0 if n contains a squared factor (other than 1). An important relation is the Möbius inversion formula, which states that if g(n)==(∑_(d | n))f(d) for all n, then f(n)==(∑_(d | n))μ(d)g(n/d), where the sums are over all positive integers d that divide n.

The divisor function (Subscript[σ, k])(n) is the sum of the k(^th) powers of the divisors of n. The function (Subscript[σ, 0])(n) gives the total number of divisors of n, and is variously denoted d(n), ν(n) and τ(n). The function (Subscript[σ, 1])(n), equal to the sum of the divisors of n, is often denoted σ(n).

For prime n, ϕ(n)==n-1:

EulerPhi[17]

The result is 1, as guaranteed by Fermat's little theorem:

PowerMod[3,%,17]

This gives a list of all the divisors of 24:

Divisors[24]

(Subscript[σ, 0])(n) gives the total number of distinct divisors of 24:

DivisorSigma[0,24]

The function (RefLink[DivisorSum, paclet:ref/DivisorSum])[n,form] represents the sum of form[i] for all i that divide n. (RefLink[DivisorSum, paclet:ref/DivisorSum])[n,form,cond] includes only those divisors for which cond[i] gives (RefLink[True, paclet:ref/True]).

This gives a list of sums for the divisors of five positive integers:

Table[DivisorSum[n,#&],{n,5}]

This imposes the condition that the value of each divisor i must be less than 6:

Table[DivisorSum[n,#&,#<6&],{n,11,15}]

The Jacobi symbol (RefLink[JacobiSymbol, paclet:ref/JacobiSymbol])[n,m] reduces to the Legendre symbol ((n/m)) when m is an odd prime. The Legendre symbol is equal to zero if n is divisible by m; otherwise it is equal to 1 if n is a quadratic residue modulo the prime m, and to -1 if it is not. An integer n relatively prime to m is said to be a quadratic residue modulo m if there exists an integer k such that (k^2)≡nmodm. The full Jacobi symbol is a product of the Legendre symbols ((n/(Subscript[p, i]))) for each of the prime factors (Subscript[p, i]) such that m==(∏_i)(Subscript[p, i]).

The extended GCD (RefLink[ExtendedGCD, paclet:ref/ExtendedGCD])[(Subscript[n, 1]),(Subscript[n, 2]),…] gives a list {g,{(Subscript[r, 1]),(Subscript[r, 2]),…}} where g is the greatest common divisor of the (Subscript[n, i]), and the (Subscript[r, i]) are integers such that g==(Subscript[r, 1])(Subscript[n, 1])+(Subscript[r, 2])(Subscript[n, 2])+…. The extended GCD is important in finding integer solutions to linear Diophantine equations.

The first number in the list is the GCD of 105 and 196:

ExtendedGCD[105,196]

The second pair of numbers satisfies g==r m+s n:

-13 105+7 196

The multiplicative order function (RefLink[MultiplicativeOrder, paclet:ref/MultiplicativeOrder])[k,n] gives the smallest integer m such that (k^m)≡1modn. Then m is known as the order of k modulo n. The notation (Subscript[ord, n])(k) is occasionally used.

The generalized multiplicative order function (RefLink[MultiplicativeOrder, paclet:ref/MultiplicativeOrder])[k,n,{(Subscript[r, 1]),(Subscript[r, 2]),…}] gives the smallest integer m such that (k^m)≡(Subscript[r, i])modn for some i. (RefLink[MultiplicativeOrder, paclet:ref/MultiplicativeOrder])[k,n,{-1,1}] is sometimes known as the suborder function of k modulo n, denoted (Subscript[sord, n])(k). (RefLink[MultiplicativeOrder, paclet:ref/MultiplicativeOrder])[k,n,{a}] is sometimes known as the discrete log of a with respect to the base k modulo n.

The Carmichael function or least universal exponent λ(n) gives the smallest integer m such that (k^m)≡1modn for all integers k relatively prime to n.

Continued fractions.

This generates the first 10 terms in the continued fraction representation for π:

ContinuedFraction[Pi,10]

This reconstructs the number represented by the list of continued fraction terms:

FromContinuedFraction[%]

The result is close to π:

N[%]

This gives directly a rational approximation to π:

Rationalize[Pi,1/1000]

Continued fractions appear in many number theoretic settings. Rational numbers have terminating continued fraction representations. Quadratic irrational numbers have continued fraction representations that become repetitive.

Complete representations for numbers.

The continued fraction representation of (Sqrt[79]) starts with the term 8, then involves a sequence of terms that repeat forever:

ContinuedFraction[Sqrt[79]]

This reconstructs (Sqrt[79]) from its continued fraction representation:

FromContinuedFraction[%]

This number is a quadratic irrational:

QuadraticIrrationalQ[ Sqrt[79]]

This shows the recurring sequence of decimal digits in 3/7:

RealDigits[3/7]

(RefLink[FromDigits, paclet:ref/FromDigits]) reconstructs the original number:

FromDigits[%]

Continued fraction convergents are often used to approximate irrational numbers by rational ones. Those approximations alternate from above and below, and converge exponentially in the number of terms. Furthermore, a convergent p/q of a simple continued fraction is better than any other rational approximation with denominator less than or equal to q.

Continued fraction convergents.

This gives a list of rational approximations of 101/9801, derived from its continued fraction expansion:

Convergents[ 101/9801 ]

This lists only the first 10 convergents:

Convergents[ 10201/96059601, 10 ]

This lists successive rational approximations to π, until the numerical precision is exhausted:

Convergents[ N[ Pi ] ]

With an exact irrational number, you have to explicitly ask for a certain number of terms:

Convergents[ Pi, 10 ]

Functions for integer lattices.

The lattice reduction function (RefLink[LatticeReduce, paclet:ref/LatticeReduce])[{(Subscript[v, 1]),(Subscript[v, 2]),…}] is used in several kinds of modern algorithms. The basic idea is to think of the vectors (Subscript[v, k]) of integers as defining a mathematical lattice. Any vector representing a point in the lattice can be written as a linear combination of the form ∑(Subscript[c, k]) (Subscript[v, k]), where the (Subscript[c, k]) are integers. For a particular lattice, there are many possible choices of the "basis vectors" (Subscript[v, k]). What (RefLink[LatticeReduce, paclet:ref/LatticeReduce]) does is to find a reduced set of basis vectors (Subscript[(OverBar[v]), k]) for the lattice, with certain special properties.

Three unit vectors along the three coordinate axes already form a reduced basis:

LatticeReduce[{{1,0,0},{0,1,0},{0,0,1}}]

This gives the reduced basis for a lattice in four-dimensional space specified by three vectors:

l=LatticeReduce[{{1,0,0,12345},{0,1,0,12435},{0,0,1,12354}}]

Notice that in the last example, (RefLink[LatticeReduce, paclet:ref/LatticeReduce]) replaces vectors that are nearly parallel by vectors that are more perpendicular. In the process, it finds some quite short basis vectors.

For a matrix m, (RefLink[HermiteDecomposition, paclet:ref/HermiteDecomposition]) gives matrices u and r such that u is unimodular, u.m==r, and r is in reduced row echelon form. In contrast to (RefLink[RowReduce, paclet:ref/RowReduce]), pivots may be larger than 1 because there are no fractions in the ring of integers. Entries above a pivot are minimized by subtracting appropriate multiples of the pivot row.

In this case, the original matrix is recovered because it was in row echelon form:

{u,r}=HermiteDecomposition[l]

This satisfies the required identities:

{Abs[Det[u]]==1,u.l==r}

Here the second matrix has some pivots larger than 1, and nonzero entries over pivots:

HermiteDecomposition[{{-2,1,1},{5,9,4},{-4,2,-11}}]

Digit count function.

Here are the digits in the base 2 representation of the number 77:

IntegerDigits[77,2]

This directly computes the number of ones in the base 2 representation:

DigitCount[77,2,1]

The plot of the digit count function is self-similar:

ListLinePlot[Table[DigitCount[n,2,1],{n,128}]]

Bitwise operations.

Bitwise operations act on integers represented as binary bits. (RefLink[BitAnd, paclet:ref/BitAnd])[(Subscript[n, 1]),(Subscript[n, 2]),…] yields the integer whose binary bit representation has ones at positions where the binary bit representations of all of the (Subscript[n, i]) have ones. (RefLink[BitOr, paclet:ref/BitOr])[(Subscript[n, 1]),(Subscript[n, 2]),…] yields the integer with ones at positions where any of the (Subscript[n, i]) have ones. (RefLink[BitXor, paclet:ref/BitXor])[(Subscript[n, 1]),(Subscript[n, 2])] yields the integer with ones at positions where (Subscript[n, 1]) or (Subscript[n, 2]) but not both have ones. (RefLink[BitXor, paclet:ref/BitXor])[(Subscript[n, 1]),(Subscript[n, 2]),…] has ones where an odd number of the (Subscript[n, i]) have ones.

This finds the bitwise AND of the numbers 23 and 29 entered in base 2:

BaseForm[BitAnd[2^^10111,2^^11101],2]

Bitwise operations are used in various combinatorial algorithms. They are also commonly used in manipulating bitfields in low-level computer languages. In such languages, however, integers normally have a limited number of digits, typically a multiple of 8. Bitwise operations in the Wolfram Language in effect allow integers to have an unlimited number of digits. When an integer is negative, it is taken to be represented in two's complement form, with an infinite sequence of ones on the left. This allows (RefLink[BitNot, paclet:ref/BitNot])[n] to be equivalent simply to -1-n.

Testing for a squared factor.

(RefLink[SquareFreeQ, paclet:ref/SquareFreeQ])[n] checks to see if n has a square prime factor. This is done by computing (RefLink[MoebiusMu, paclet:ref/MoebiusMu])[n] and seeing if the result is zero; if it is, then n is not squarefree, otherwise it is. Computing (RefLink[MoebiusMu, paclet:ref/MoebiusMu])[n] involves finding the smallest prime factor q of n. If n has a small prime factor (less than or equal to 1223), this is very fast. Otherwise, (RefLink[FactorInteger, paclet:ref/FactorInteger]) is used to find q.

This product of primes contains no squared factors:

SquareFreeQ[2 3 5 7]

The square number 4 divides 60:

SquareFreeQ[60]

(RefLink[SquareFreeQ, paclet:ref/SquareFreeQ]) can handle large integers:

SquareFreeQ[(2^101)-1]

Finding prime numbers.

(RefLink[NextPrime, paclet:ref/NextPrime])[n] finds the smallest prime p such that p>n. The algorithm does a direct search using (RefLink[PrimeQ, paclet:ref/PrimeQ]) on the odd numbers greater than n.

This gives the next prime after 10:

NextPrime[10]

Even for large numbers, the next prime can be computed rather quickly:

NextPrime[(10^100)]//Timing

This gives the largest prime less than 34:

-NextPrime[-34]

For (RefLink[RandomPrime, paclet:ref/RandomPrime])[{min,max}] and (RefLink[RandomPrime, paclet:ref/RandomPrime])[max], a random prime p is obtained by randomly selecting from a prime lookup table if max is small and by a random search of integers in the range if max is large. If no prime exists in the specified range, the input is returned unevaluated with an error message.

Here is a random prime between 10 and 100:

RandomPrime[{10,100}]

Testing for involving prime powers.

The algorithm for (RefLink[PrimePowerQ, paclet:ref/PrimePowerQ]) involves first computing the least prime factor p of n and then attempting division by p until either 1 is obtained, in which case n is a prime power, or until division is no longer possible, in which case n is not a prime power.

Here is a number that is a power of a single prime:

PrimePowerQ[12167]

Over the (RefLink[GaussianIntegers, paclet:ref/GaussianIntegers]) this is a prime power:

PrimePowerQ[(1+I)^3]

Solving simultaneous congruences.

The Chinese remainder theorem states that a certain class of simultaneous congruences always has a solution. (RefLink[ChineseRemainder, paclet:ref/ChineseRemainder])[(Subscript[list, 1]),(Subscript[list, 2])] finds the smallest non-negative integer r such that (RefLink[Mod, paclet:ref/Mod])[r,(Subscript[list, 2])] is (Subscript[list, 1]). The solution is unique modulo the least common multiple of the elements of (Subscript[list, 2]).

This means that 244≡0 mod 4, 244≡1 mod 9, and 244≡2 mod 121:

ChineseRemainder[{0,1,2},{4,9,121}]

This confirms the result:

Mod[244,{4,9,121}]

Longer lists are still quite fast:

ChineseRemainder[Range[20],Prime[Range[20]]]

Computing primitive roots.

(RefLink[PrimitiveRoot, paclet:ref/PrimitiveRoot])[n] returns a generator for the group of numbers relatively prime to n under multiplication mod n. This has a generator if and only if n is 2, 4, a power of an odd prime, or twice a power of an odd prime. If n is a prime or prime power, the least positive primitive root will be returned.

Here is a primitive root of 5:

PrimitiveRoot[5]

This confirms that it does generate the group:

Sort[Mod[(2^(Range[4])),5]]

Here is a primitive root of a prime power:

PrimitiveRoot[(1093^3)]

Here is a primitive root of twice a prime power:

PrimitiveRoot[2 (5^5)]

If the argument is composite and not a prime power or twice a prime power, the function does not evaluate:

PrimitiveRoot[11 13]

Representing an integer as a sum of squares or other powers.

Here are the representations of 101 as a sum of 3 squares:

PowersRepresentations[101,3,2]