[Top] [Up] [Previous] [Next] [Index]

# 14 Integers

### Sections

1. Elementary Operations for Integers
2. Quotients and Remainders
3. Prime Integers and Factorization
4. Residue Class Rings
5. Random Sources

One of the most fundamental datatypes in every programming language is the integer type. GAP is no exception.

GAP integers are entered as a sequence of decimal digits optionally preceded by a `+` sign for positive integers or a `-` sign for negative integers. The size of integers in GAP is only limited by the amount of available memory, so you can compute with integers having thousands of digits.

    gap> -1234;
    -1234
    gap> 123456789012345678901234567890123456789012345678901234567890;
    123456789012345678901234567890123456789012345678901234567890

Many more functions that are mainly related to the prime residue group of integers modulo an integer are described in chapter Number Theory, and functions dealing with combinatorics can be found in chapter Combinatorics.

- `Integers V`
- `PositiveIntegers V`
- `NonnegativeIntegers V`

  These global variables represent the ring of integers and the semirings of positive and nonnegative integers, respectively.

      gap> Size( Integers ); 2 in Integers;
      infinity
      true

- `IsIntegers(` obj`) C`
- `IsPositiveIntegers(` obj`) C`
- `IsNonnegativeIntegers(` obj`) C`

  are the defining categories for the domains `Integers`, `PositiveIntegers`, and `NonnegativeIntegers`.

      gap> IsIntegers( Integers );  IsIntegers( Rationals );  IsIntegers( 7 );
      true
      false
      false

  `Integers` is a subset of `Rationals`, which is a subset of `Cyclotomics`. See Chapter Cyclotomic Numbers for arithmetic operations and comparison of integers.

  ## 14.1 Elementary Operations for Integers

- `IsInt(` obj`) C`

  Every rational integer lies in the category `IsInt`, which is a subcategory of `IsRat` (see Rational Numbers).

- `IsPosInt(` obj`) C`

  Every positive integer lies in the category `IsPosInt`.

- `Int(` elm`) A`

  `Int` returns an integer int whose meaning depends on the type of elm.

  If elm is a rational number (see Rational Numbers) then int is the integer part of the quotient of numerator and denominator of elm (see QuoInt).

  If elm is an element of a finite prime field (see Chapter Finite Fields) then int is the smallest nonnegative integer such that ``elm`=` int`* One(` elm`)`.

  If elm is a string (see Chapter Strings and Characters) consisting of digits `'0'`, `'1'`, …, `'9'` and `'-'` (at the first position) then int is the integer described by this string. The operation `String` (see String) can be used to compute a string for rational integers, in fact for all cyclotomics.

      gap> Int( 4/3 );  Int( -2/3 );
      1
      0
      gap> int:= Int( Z(5) );  int * One( Z(5) );
      2
      Z(5)
      gap> Int( "12345" );  Int( "-27" );  Int( "-27/3" );
      12345
      -27
      fail

- `IsEvenInt(` n`) F`

  tests if the integer n is divisible by 2.

- `IsOddInt(` n`) F`

  tests if the integer n is not divisible by 2.

- `AbsInt(` n`) F`

  `AbsInt` returns the absolute value of the integer n, i.e., n if n is positive, -n if n is negative and 0 if n is 0.

  `AbsInt` is a special case of the general operation `EuclideanDegree` see EuclideanDegree).

  See also AbsoluteValue.

      gap> AbsInt( 33 );
      33
      gap> AbsInt( -214378 );
      214378
      gap> AbsInt( 0 );
      0

- `SignInt(` n`) F`

  `SignInt` returns the sign of the integer n, i.e., 1 if n is positive, -1 if n is negative and 0 if n is 0.

      gap> SignInt( 33 );
      1
      gap> SignInt( -214378 );
      -1
      gap> SignInt( 0 );
      0

- `LogInt(` n`,` base`) F`

  `LogInt` returns the integer part of the logarithm of the positive integer n with respect to the positive integer base, i.e., the largest positive integer exp such that baseexp ≤ n. `LogInt` will signal an error if either n or base is not positive.

  For base 2 this is very efficient because the internal binary representation of the integer is used.

      gap> LogInt( 1030, 2 );
      10
      gap> 2^10;
      1024
      gap> LogInt( 1, 10 );
      0

- `RootInt(` n`) F`
- `RootInt(` n`,` k`) F`

  `RootInt` returns the integer part of the kth root of the integer n. If the optional integer argument k is not given it defaults to 2, i.e., `RootInt` returns the integer part of the square root in this case.

  If n is positive, `RootInt` returns the largest positive integer r such that rk ≤ n. If n is negative and k is odd `RootInt` returns `-RootInt( -`n`,` k`)`. If n is negative and k is even `RootInt` will cause an error. `RootInt` will also cause an error if k is 0 or negative.

      gap> RootInt( 361 );
      19
      gap> RootInt( 2 * 10^12 );
      1414213
      gap> RootInt( 17000, 5 );
      7
      gap> 7^5;
      16807

- `SmallestRootInt(` n`) F`

  `SmallestRootInt` returns the smallest root of the integer n.

  The smallest root of an integer n is the integer r of smallest absolute value for which a positive integer k exists such that n = rk.

      gap> SmallestRootInt( 2^30 );
      2
      gap> SmallestRootInt( -(2^30) );
      -4

  Note that (−2)30 = +(230).

      gap> SmallestRootInt( 279936 );
      6
      gap> LogInt( 279936, 6 );
      7
      gap> SmallestRootInt( 1001 );
      1001

- `Random( Integers )`

  `Random` for integers returns pseudo random integers between -10 and 10 distributed according to a binomial distribution. To generate uniformly distributed integers from a range, use the construct 'Random( [ low .. high ] )'. (Also see Random.)

  ## 14.2 Quotients and Remainders

- `QuoInt(` n`,` m`) F`

  `QuoInt` returns the integer part of the quotient of its integer operands.

  If n and m are positive `QuoInt(` n`,` m`)` is the largest positive integer q such that q * m ≤ n . If n or m or both are negative the absolute value of the integer part of the quotient is the quotient of the absolute values of n and m, and the sign of it is the product of the signs of n and m.

  `QuoInt` is used in a method for the general operation `EuclideanQuotient` (see EuclideanQuotient).

      gap> QuoInt(5,3);  QuoInt(-5,3);  QuoInt(5,-3);  QuoInt(-5,-3);
      1
      -1
      -1
      1

- `BestQuoInt(` n`,` m`) F`

  `BestQuoInt` returns the best quotient q of the integers n and m. This is the quotient such that ``n`-`q`*`m`` has minimal absolute value. If there are two quotients whose remainders have the same absolute value, then the quotient with the smaller absolute value is chosen.

      gap> BestQuoInt( 5, 3 );  BestQuoInt( -5, 3 );
      2
      -2

- `RemInt(` n`,` m`) F`

  `RemInt` returns the remainder of its two integer operands.

  If m is not equal to zero `RemInt(` n`,` m`) =` n`-` m`* QuoInt(` n`,` m`)`. Note that the rules given for `QuoInt` imply that `RemInt(` n`,` m`)` has the same sign as n and its absolute value is strictly less than the absolute value of m. Note also that `RemInt(` n`,` m`) =` n `mod` m`` when both n and m are nonnegative. Dividing by 0 signals an error.

  `RemInt` is used in a method for the general operation `EuclideanRemainder` (see EuclideanRemainder).

      gap> RemInt(5,3);  RemInt(-5,3);  RemInt(5,-3);  RemInt(-5,-3);
      2
      -2
      2
      -2

- `GcdInt(` m`,` n`) F`

  `GcdInt` returns the greatest common divisor of its two integer operands m and n, i.e., the greatest integer that divides both m and n. The greatest common divisor is never negative, even if the arguments are. We define `GcdInt(` m`, 0 ) = GcdInt( 0,` m`) = AbsInt(` m`)` and `GcdInt( 0, 0 ) = 0`.

  `GcdInt` is a method used by the general function `Gcd` (see Gcd).

      gap> GcdInt( 123, 66 );
      3

- `Gcdex(` m`,` n`) F`

  returns a record g describing the extended greatest common divisor of m and n. The component `gcd` is this gcd, the components `coeff1` and `coeff2` are integer cofactors such that ``g`.gcd =` g`.coeff1 *` m`+` g`.coeff2 *` n``, and the components `coeff3` and `coeff4` are integer cofactors such that `0 =` g`.coeff3 *` m`+` g`.coeff4 *` n``.

  If m and n both are nonzero, `AbsInt(` g`.coeff1 )` is less than or equal to `AbsInt(`n`) / (2 *` g`.gcd)` and `AbsInt(` g`.coeff2 )` is less than or equal to `AbsInt(`m`) / (2 *` g`.gcd)`.

  If m or n or both are zero `coeff3` is `-`n`/` g`.gcd` and `coeff4` is ``m`/` g`.gcd`.

  The coefficients always form a unimodular matrix, i.e., the determinant ``g`.coeff1 *` g`.coeff4 -` g`.coeff3 *` g`.coeff2` is 1 or −1.

      gap> Gcdex( 123, 66 );
      rec( gcd := 3, coeff1 := 7, coeff2 := -13, coeff3 := -22, coeff4 := 41 )

  This means 3 = 7 * 123 − 13 * 66, 0 = −22 * 123 + 41 * 66.

      gap> Gcdex( 0, -3 );
      rec( gcd := 3, coeff1 := 0, coeff2 := -1, coeff3 := 1, coeff4 := 0 )
      gap> Gcdex( 0, 0 );
      rec( gcd := 0, coeff1 := 1, coeff2 := 0, coeff3 := 0, coeff4 := 1 )

- `LcmInt(` m`,` n`) F`

  returns the least common multiple of the integers m and n.

  `LcmInt` is a method used by the general function `Lcm`.

      gap> LcmInt( 123, 66 );
      2706

- `CoefficientsQadic(` i`,` q`) F`

  returns the q-adic representation of the integer i as a list l of coefficients where i = ∑j=0 qj ·l[j+1].

- `CoefficientsMultiadic(` ints`,` int`) F`

  returns the multiadic expansion of the integer int modulo the integers given in ints (in ascending order). It returns a list of coefficients in the reverse order to that in ints.

- `ChineseRem(` moduli`,` residues`) F`

  `ChineseRem` returns the combination of the residues modulo the moduli, i.e., the unique integer c from `[0..Lcm(`moduli`)-1]` such that ``c`=` residues`[i]` modulo ``moduli`[i]` for all i, if it exists. If no such combination exists `ChineseRem` signals an error.

  Such a combination does exist if and only if ``residues`[`i`]=`residues`[`k`]` mod `Gcd(`moduli`[`i`],`moduli`[`k`])` for every pair i, k. Note that this implies that such a combination exists if the moduli are pairwise relatively prime. This is called the Chinese remainder theorem.

      gap> ChineseRem( [ 2, 3, 5, 7 ], [ 1, 2, 3, 4 ] );
      53
      gap> ChineseRem( [ 6, 10, 14 ], [ 1, 3, 5 ] );
      103

      gap> ChineseRem( [ 6, 10, 14 ], [ 1, 2, 3 ] );
      Error, the residues must be equal modulo 2 called from
      <function>( <arguments> ) called from read-eval-loop
      Entering break read-eval-print loop ...
      you can 'quit;' to quit to outer loop, or
      you can 'return;' to continue
      brk> gap>

- `PowerModInt(` r`,` e`,` m`) F`

  returns re mod m for integers r,e and m (e ≥ 0). Note that using ``r`^` e `mod` m`` will generally be slower, because it can not reduce intermediate results the way `PowerModInt` does but would compute ``r`^`e`` first and then reduce the result afterwards.

  `PowerModInt` is a method for the general operation `PowerMod`.

  ## 14.3 Prime Integers and Factorization

- `Primes V`

  `Primes` is a strictly sorted list of the 168 primes less than 1000.

  This is used in `IsPrimeInt` and `FactorsInt` to cast out small primes quickly.

      gap> Primes[1];
      2
      gap> Primes[100];
      541

- `IsPrimeInt(` n`) F`
- `IsProbablyPrimeInt(` n`) F`

  `IsPrimeInt` returns `false` if it can prove that n is composite and `true` otherwise. By convention `IsPrimeInt(0) = IsPrimeInt(1) = false` and we define `IsPrimeInt( -`n`) = IsPrimeInt(` n`)`.

  `IsPrimeInt` will return `true` for every prime n. `IsPrimeInt` will return `false` for all composite n < 1013 and for all composite n that have a factor p < 1000. So for integers n < 1013, `IsPrimeInt` is a proper primality test. It is conceivable that `IsPrimeInt` may return `true` for some composite n > 1013, but no such n is currently known. So for integers n > 1013, `IsPrimeInt` is a probable-primality test. `IsPrimeInt` will issue a warning when its argument is probably prime but not a proven prime. (The function `IsProbablyPrimeInt` will do the same calculations but not issue a warning.) The warning can be switched off by `SetInfoLevel( InfoPrimeInt, 0 );`, the default level is 1.

  If composites that fool `IsPrimeInt` do exist, they would be extremely rare, and finding one by pure chance might be less likely than finding a bug in GAP. We would appreciate being informed about any example of a composite number n for which `IsPrimeInt` returns `true`.

  `IsPrimeInt` is a deterministic algorithm, i.e., the computations involve no random numbers, and repeated calls will always return the same result. `IsPrimeInt` first does trial divisions by the primes less than 1000. Then it tests that n is a strong pseudoprime w.r.t. the base 2. Finally it tests whether n is a Lucas pseudoprime w.r.t. the smallest quadratic nonresidue of n. A better description can be found in the comment in the library file `integer.gi`.

  The time taken by `IsPrimeInt` is approximately proportional to the third power of the number of digits of n. Testing numbers with several hundreds digits is quite feasible.

  `IsPrimeInt` is a method for the general operation `IsPrime`.

  Remark: In future versions of GAP we hope to change the definition of `IsPrimeInt` to return `true` only for proven primes (currently, we lack a sufficiently good primality proving function). In applications, use explicitly `IsPrimeInt` or `IsProbablePrimeInt` with this change in mind.

      gap> IsPrimeInt( 2^31 - 1 );
      true
      gap> IsPrimeInt( 10^42 + 1 );
      false

- `IsPrimePowerInt(` n`) F`

  `IsPrimePowerInt` returns `true` if the integer n is a prime power and `false` otherwise.

  n is a prime power if there exists a prime p and a positive integer i such that pi = n. If n is negative the condition is that there must exist a negative prime p and an odd positive integer i such that pi = n. 1 and -1 are not prime powers.

  Note that `IsPrimePowerInt` uses `SmallestRootInt` (see SmallestRootInt) and a probable-primality test (see IsPrimeInt).

      gap> IsPrimePowerInt( 31^5 );
      true
      gap> IsPrimePowerInt( 2^31-1 );  # 2^31-1 is actually a prime
      true
      gap> IsPrimePowerInt( 2^63-1 );
      false
      gap> Filtered( [-10..10], IsPrimePowerInt );
      [ -8, -7, -5, -3, -2, 2, 3, 4, 5, 7, 8, 9 ]

- `NextPrimeInt(` n`) F`

  `NextPrimeInt` returns the smallest prime which is strictly larger than the integer n.

  Note that `NextPrimeInt` uses a probable-primality test (see IsPrimeInt).

      gap> NextPrimeInt( 541 ); NextPrimeInt( -1 );
      547
      2

- `PrevPrimeInt(` n`) F`

  `PrevPrimeInt` returns the largest prime which is strictly smaller than the integer n.

  Note that `PrevPrimeInt` uses a probable-primality test (see IsPrimeInt).

      gap> PrevPrimeInt( 541 ); PrevPrimeInt( 1 );
      523
      -2

- `FactorsInt(` n`) F`
- `FactorsInt(` n`: RhoTrials :=` trials`) F`

  `FactorsInt` returns a list of prime factors of the integer n.

  If the ith power of a prime divides n this prime appears i times. The list is sorted, that is the smallest prime factors come first. The first element has the same sign as n, the others are positive. For any integer n it holds that `Product( FactorsInt(` n`) ) =` n``.

  Note that `FactorsInt` uses a probable-primality test (see IsPrimeInt). Thus `FactorsInt` might return a list which contains composite integers. In such a case you will get a warning about the use of a probable prime. You can switch off these warnings by `SetInfoLevel(InfoPrimeInt, 0);`.

  The time taken by `FactorsInt` is approximately proportional to the square root of the second largest prime factor of n, which is the last one that `FactorsInt` has to find, since the largest factor is simply what remains when all others have been removed. Thus the time is roughly bounded by the fourth root of n. `FactorsInt` is guaranteed to find all factors less than 106 and will find most factors less than 1010. If n contains multiple factors larger than that `FactorsInt` may not be able to factor n and will then signal an error.

  `FactorsInt` is used in a method for the general operation `Factors`.

  In the second form, FactorsInt calls FactorsRho with a limit of trials on the number of trials is performs. The default is 8192.

      gap> FactorsInt( -Factorial(6) );
      [ -2, 2, 2, 2, 3, 3, 5 ]
      gap> Set( FactorsInt( Factorial(13)/11 ) );
      [ 2, 3, 5, 7, 13 ]
      gap> FactorsInt( 2^63 - 1 );
      [ 7, 7, 73, 127, 337, 92737, 649657 ]
      gap> FactorsInt( 10^42 + 1 );
      #I  IsPrimeInt: probably prime, but not proven: 4458192223320340849
      [ 29, 101, 281, 9901, 226549, 121499449, 4458192223320340849 ]

- `PartialFactorization(` n`) O`
- `PartialFactorization(` n`,` effort`) O`

  `PartialFactorization` returns a partial factorization of the integer n. No assertions are made about the primality of the factors, except of those mentioned below.

  The argument effort, if given, specifies how intensively the function should try to determine factors of n. The default is effort = 5.

  -
    If effort = 0, trial division by the primes below 100 is done. Returned factors below 104 are guaranteed to be prime.
  -
    If effort = 1, trial division by the primes below 1000 is done. Returned factors below 106 are guaranteed to be prime.
  -
    If effort = 2, additionally trial division by the numbers in the lists `Primes2` and `ProbablePrimes2` is done, and perfect powers are detected. Returned factors below 106 are guaranteed to be prime.
  -
    If effort = 3, additionally `FactorsRho` (Pollard's Rho) with RhoTrials = 256 is used.
  -
    If effort = 4, as above, but RhoTrials = 2048.
  -
    If effort = 5, as above, but RhoTrials = 8192. Returned factors below 1012 are guaranteed to be prime, and all prime factors below 106 are guaranteed to be found.
  -
    If effort = 6 and FactInt is loaded, in addition to the above quite a number of special cases are handled.
  -
    If effort = 7 and FactInt is loaded, the only thing which is not attempted to obtain a full factorization into Baillie-Pomerance-Selfridge-Wagstaff pseudoprimes is the application of the MPQS to a remaining composite with more than 50 decimal digits.
  Increasing the value of the argument effort by one usually results in an increase of the runtime requirements by a factor of (very roughly!) 3 to 10.

      gap> List([0..5],i->PartialFactorization(7^64-1,i));
      [ [ 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 5, 5, 17,
            1868505648951954197516197706132003401892793036353 ],
        [ 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 5, 5, 17, 353,
            5293217135841230021292344776577913319809612001 ],
        [ 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 5, 5, 17, 353, 134818753, 47072139617,
            531968664833, 1567903802863297 ],
        [ 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 5, 5, 17, 353, 1201, 169553, 7699649,
            134818753, 47072139617, 531968664833 ],
        [ 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 5, 5, 17, 353, 1201, 169553, 7699649,
            134818753, 47072139617, 531968664833 ],
        [ 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 5, 5, 17, 353, 1201, 169553, 7699649,
            134818753, 47072139617, 531968664833 ] ]

- `PrintFactorsInt(` n`) F`

  prints the prime factorization of the integer n in human-readable form.

      gap> PrintFactorsInt( Factorial( 7 ) ); Print( "\n" );
      2^4*3^2*5*7

- `PrimePowersInt(` n`) F`

  returns the prime factorization of the integer n as a list [ p1, e1, …, pn, en ] with n = ∏i=1n piei.

      gap> PrimePowersInt( Factorial( 7 ) );
      [ 2, 4, 3, 2, 5, 1, 7, 1 ]

- `DivisorsInt(` n`) F`

  `DivisorsInt` returns a list of all divisors of the integer n. The list is sorted, so that it starts with 1 and ends with n. We define that `Divisors( -`n`) = Divisors(` n`)`.

  Since the set of divisors of 0 is infinite calling `DivisorsInt( 0 )` causes an error.

  `DivisorsInt` may call `FactorsInt` to obtain the prime factors. `Sigma` and `Tau` (see Sigma and Tau) compute the sum and the number of positive divisors, respectively.

      gap> DivisorsInt( 1 ); DivisorsInt( 20 ); DivisorsInt( 541 );
      [ 1 ]
      [ 1, 2, 4, 5, 10, 20 ]
      [ 1, 541 ]

  ## 14.4 Residue Class Rings

- ``r`/` s `mod` n``

  If r, s and n are integers, ``r`/` s`` as a reduced fraction is ``p`/` q``, and q and n are coprime, then ``r`/` s `mod` n`` is defined to be the product of p and the inverse of q modulo n. See Section Arithmetic Operators for more details and definitions.

  With the above definition, `4 / 6 mod 32` equals `2 / 3 mod 32` and hence exists (and is equal to 22), despite the fact that 6 has no inverse modulo 32.

- `ZmodnZ(` n`) F`
- `ZmodpZ(` p`) F`
- `ZmodpZNC(` p`) F`

  `ZmodnZ` returns a ring R isomorphic to the residue class ring of the integers modulo the positive integer n. The element corresponding to the residue class of the integer i in this ring can be obtained by i * `One`( R ), and a representative of the residue class corresponding to the element x ∈ R can be computed by `Int`( x ).

  `ZmodnZ(` n`)` is equivalent to `Integers mod` n``.

  `ZmodpZ` does the same if the argument p is a prime integer, additionally the result is a field. `ZmodpZNC` omits the check whether p is a prime.

  Each ring returned by these functions contains the whole family of its elements if n is not a prime, and is embedded into the family of finite field elements of characteristic n if n is a prime.

- `ZmodnZObj(` Fam`,` r`) O`
- `ZmodnZObj(` r`,` n`) O`

  If the first argument is a residue class family Fam then `ZmodnZObj` returns the element in Fam whose coset is represented by the integer r. If the two arguments are an integer r and a positive integer n then `ZmodnZObj` returns the element in `ZmodnZ(` n`)` (see ZmodnZ) whose coset is represented by the integer r.

      gap> r:= ZmodnZ(15);
      (Integers mod 15)
      gap> fam:=ElementsFamily(FamilyObj(r));;
      gap> a:= ZmodnZObj(fam,9);
      ZmodnZObj( 9, 15 )
      gap> a+a;
      ZmodnZObj( 3, 15 )
      gap> Int(a+a);
      3

- `IsZmodnZObj(` obj`) C`
- `IsZmodnZObjNonprime(` obj`) C`
- `IsZmodpZObj(` obj`) C`
- `IsZmodpZObjSmall(` obj`) C`
- `IsZmodpZObjLarge(` obj`) C`

  The elements in the rings Z / n Z are in the category `IsZmodnZObj`. If n is a prime then the elements are of course also in the category `IsFFE` (see IsFFE), otherwise they are in `IsZmodnZObjNonprime`. `IsZmodpZObj` is an abbreviation of `IsZmodnZObj and IsFFE`. This category is the disjoint union of `IsZmodpZObjSmall` and `IsZmodpZObjLarge`, the former containing all elements with n at most `MAXSIZE_GF_INTERNAL`.

  The reasons to distinguish the prime case from the nonprime case are

  - that objects in `IsZmodnZObjNonprime` have an external representation (namely the residue in the range [ 0, 1, …, n−1 ]),
  - that the comparison of elements can be defined as comparison of the residues, and
  - that the elements lie in a family of type `IsZmodnZObjNonprimeFamily` (note that for prime n, the family must be an `IsFFEFamily`).

  The reasons to distinguish the small and the large case are that for small n the elements must be compatible with the internal representation of finite field elements, whereas we are free to define comparison as comparison of residues for large n.

  Note that we cannot claim that every finite field element of degree 1 is in `IsZmodnZObj`, since finite field elements in internal representation may not know that they lie in the prime field.

  The residue class rings are rings, thus all operations for rings (see Chapter Rings) apply. See also Chapters Finite fields and Number theory.

  ## 14.5 Random Sources

  GAP provides `Random` methods (see Random) for many collections of objects. On a lower level these methods use random sources which provide random integers and random choices from lists.

- `IsRandomSource(` rs`) C`

  This is the category of random source objects rs which are defined to have methods available for the following operations which are explained in more detail below: `Random(` rs`,` list`)` giving a random element of a list, `Random(` rs`,` low`,` high`)` giving a random integer between low and high (inclusive), `Init`, `State` and `Reset`.

  Use `RandomSource` (see RandomSource) to construct new random sources.

  One idea behind providing several independent (pseudo) random sources is to make algorithms which use some sort of random choices deterministic. They can use their own new random source created with a fixed seed and so do exactly the same in different calls.

  Random source objects lie in the family `RandomSourcesFamily`.

- `Random(` rs`,` list`) O`
- `Random(` rs`,` low`,` high`) O`

  This operation returns a random element from list list, or an integer in the range from the given (possibly large) integers low to high, respectively. The choice should only depend on the random source rs and have no effect on other random sources.

- `State(` rs`) O`
- `Reset(` rs`) O`
- `Reset(` rs`,` seed`) O`
- `Init(` rs`) O`
- `Init(` prers`,` seed`) O`

  These are the basic operations for which random sources (see IsRandomSource) must have methods.

  `State` should return a data structure which allows to recover the state of the random source such that a sequence of random calls using this random source can be reproduced. If a random source cannot be reset (say, it uses truely random physical data) then `State` should return `fail`.

  `Reset(` rs`,` seed`)` resets the random source rs to a state described by seed, if the random source can be reset (otherwise it should do nothing). Here seed can be an output of `State` and then should reset to that state. Also, the methods should always allow integers as seed. Without the seed argument the default seed = 1 is used.

  `Init` is the constructor of a random source, it gets an empty component object which has already the correct type and should fill in the actual data which are needed. Optionally, it should allow one to specify a seed for the initial state, as explained for `Reset`.

- `IsGlobalRandomSource(` rs`) C`
- `IsGAPRandomSource(` rs`) C`
- `IsMersenneTwister(` rs`) C`
- `GlobalRandomSource V`
- `GlobalMersenneTwister V`

  Currently, the GAP library provides three types of random sources, distinguished by the three listed categories.

  `IsGlobalRandomSource` gives access to the classical global random generator which was used by GAP in previous releases. You do not need to construct new random sources of this kind which would all use the same global data structure. Just use the existing random source `GlobalRandomSource`. This uses the additive random number generator described in TACP2 (Algorithm A in 3.2.2 with lag 30).

  `IsGAPRandomSource` uses the same number generator as `IsGlobalRandomSource`, but you can create several of these random sources which generate their random numbers independently of all other random sources.

  `IsMersenneTwister` are random sources which use a fast random generator of 32 bit numbers, called the Mersenne twister. The pseudo random sequence has a period of 219937−1 and the numbers have a 623-dimensional equidistribution. For more details and the origin of the code used in the GAP kernel, see:

  `http://www.math.sci.hiroshima-u.ac.jp/ m-mat/MT/emt.html`

  Use the Mersenne twister if possible, in particular for generating many large random integers.

  There is also a predefined global random source `GlobalMersenneTwister`.

- `RandomSource(` cat`) O`
- `RandomSource(` cat`,` seed`) O`

  This operation is used to create new random sources. The first argument is the category describing the type of the random generator, an optional seed which can be an integer or a type specific data structure can be given to specify the initial state.

      gap> rs1 := RandomSource(IsMersenneTwister);
      <RandomSource in IsMersenneTwister>
      gap> state1 := State(rs1);;
      gap> l1 := List([1..10000], i-> Random(rs1, [1..6]));;
      gap> rs2 := RandomSource(IsMersenneTwister);;
      gap> l2 := List([1..10000], i-> Random(rs2, [1..6]));;
      gap> l1 = l2;
      true
      gap> l1 = List([1..10000], i-> Random(rs1, [1..6]));
      false
      gap> n := Random(rs1, 1, 2^220);
      1598617776705343302477918831699169150767442847525442557699717518961

  [Top] [Up] [Previous] [Next] [Index]

  GAP 4 manual
  October 2007