Binary powering multiplication count Created 2026-10-14 Updated 2026-10-24
For the optimized left-to-right exponentiation by squaring algorithm, let be the length of the binary expansion of a positive integer , and let be its Hamming weight, the number of digits equal to one. There are exactly digits after the leading one, and exactly remaining ones. Therefore the count is
Here counts squarings and counts further multiplications by the base; every squaring counts as one multiplication in . Assignment, digit reading, and any inversion are outside this count. The formula includes , which requires zero multiplications; define separately.
For a fixed length , the bounds are . A power of two reaches the lower bound because its Hamming weight is one; reaches the upper bound because all digits are one. For , and , giving . Thus the arithmetic operation count is in Big O notation, but inputs of similar magnitude can have different counts.
Figure 1.
Exact multiplication counts for optimized exponentiation by squaring depend on binary length and Hamming weight
. For positive exponents through , dots show , including each squaring. The dashed curves bound all counts at each binary length. Successive multiplication needs operations. The second panel compares squarings and further multiplications for exponents . These are exact counts, not timing measurements. Details.
This is a count for the specified algorithm, not a claim that it always minimizes multiplications among all methods. For instance, at the count is six, but the powers with exponents can be built in five multiplications: square, multiply by , square, square, then multiply by the already stored . Saving operations this way uses a different schedule and stored intermediate powers.
The binary powering multiplication count counts arithmetic operations. The time complexity measured in operations on individual bits also depends on operand lengths. Put , the binary length of the modulus, and let be the positive exponent's binary length. Stored residues use at most bits, and an unreduced product uses at most bits.
With ordinary long multiplication and division with remainder, one modular product costs operations on bits. Combining that cost with modular products gives
This bound includes reductions in the loop, and assumes the base has already been reduced and the exponent is available as a binary expansion. Reading the exponent takes additional work; initial reduction of a very long base depends on its input length, and an inverse for a negative exponent adds further work. More generally, if a modular product costs operations on bits, the powering loop costs . Faster multiplication and reduction methods can improve the quadratic bound.[ref]
For ordinary integer powers with , the output itself has binary digits. Even writing it takes work proportional to that length. Consequently multiplications does not imply operations on bits: the operands grow during ordinary exponentiation by squaring, whereas modular exponentiation keeps them bounded by the modulus. A squaring or multiplication by a small fixed base can also cost less than a general product, so equal counts need not mean equal running times.
Euler's criterion Created 2026-09-24 Updated 2026-10-18
For an odd prime and , Euler's criterion identifies the Legendre symbol by modular exponentiation:
Thus a quadratic residue gives one and a quadratic nonresidue gives minus one, represented by if a nonnegative remainder is used. The formula also holds when , because and both sides are zero modulo .[ref]
For example, modulo seven the exponent is three: confirms that two is a quadratic residue, while confirms that three is a quadratic nonresidue. Modulo eleven the exponent is five, and confirms that two is a quadratic nonresidue. The test answers whether a square root exists; it does not itself return the roots of .
A short proof needs only Fermat's little theorem and the root bound for a polynomial. Put . If in the prime field, then . There are already such quadratic residues. The nonzero polynomial has polynomial degree , so it has no other polynomial roots. Finally, for every nonzero , Fermat's little theorem gives . Factoring in the field shows ; every quadratic nonresidue must take the remaining value . This proves the criterion without first finding a primitive root.
For a larger original example, decide whether seven is a quadratic residue modulo the prime number . Exponentiation by squaring computes the required power without listing fifty squares:
Therefore and has no solution. Each intermediate product is reduced modulo , as in modular exponentiation. The advantage is that exponentiation by squaring uses a number of multiplications proportional to the binary digit length of the exponent rather than testing every potential square root.
The odd prime hypothesis is essential. For the composite modulus nine, , which is neither one nor minus one. Although four is a nonzero square modulo nine, , so even the square-to-one implication fails. The Jacobi symbol and Euler pseudoprime discuss different questions for odd composite moduli; they do not make this a universal square test.
For a unit modulo n and a nonnegative integer , division with remainder writes with . Euler's theorem then gives
This replaces a potentially enormous exponent by a small remainder. The exponent itself is reduced modulo Euler's totient function, while the powers are reduced modulo : these are different integer moduli.
For a worked modulo-fifteen calculation, seven is coprime to fifteen and . Therefore
Use exponentiation by squaring on the remaining exponent , reducing after each multiplication:
Thus . Modular exponentiation supplies the computation; Euler's theorem supplies the optional shortening of its exponent. Exponentiation by squaring also works for nonunit bases, without using this shortening.
The guaranteed exponent is a common return exponent and an upper bound on the shortest period; it need not be that period. The multiplicative order is the least positive return exponent for the chosen unit. The Carmichael function is the least positive return exponent that works for every unit. Their precise relation is
Either smaller return exponent can replace in exponent reduction for units. Modulo fifteen, , so gives immediately. For base four the multiplicative order is only two, smaller even than . A return at exponent eight alone does not prove that the multiplicative order is eight.[ref]
Figure 1.
Actual power periods, Carmichael function exponents and Euler return exponents
. Each row lists powers from exponent zero through eight. Highlighted first returns identify multiplicative orders; the accompanying labels distinguish a chosen base's shortest period, the common exponent for all units, and Euler's totient function. Powers of the nonunit three modulo fifteen repeat after an initial term but never return to one at a positive exponent. The final calculation compares reduction of modulo eight and modulo four. Details.
If the reduced exponent is zero, the rule gives , and still requires a unit. Applying it to the nonunit three would falsely predict ; the actual residue is six. For negative exponents, first interpret the power using a modular multiplicative inverse, as in modular exponentiation.
Kitamasa algorithm 2026-10-20
The Kitamasa algorithm evaluates a term of an order- linear recurrence by reducing powers of modulo its characteristic polynomial of a linear recurrence. If the recurrence relation is , reduce modulo by exponentiation by squaring; the resulting coefficients give as a linear combination of . Straightforward polynomial multiplication gives arithmetic operations.
Modular exponentiation Created 2026-10-06 Updated 2026-10-20
Modular exponentiation computes the remainder for an integer base , a nonnegative integer exponent , and, here, an integer modulus . It applies exponentiation by squaring while reducing after each multiplication, including each squaring. The result is the unique representative in . There is no requirement that the base be coprime to the modulus when the exponent is nonnegative.[ref]
Take , , and . Initialize ; the remaining digits give
Hence . The final operation multiplies by , since the preceding square has already been reduced. The computation never needs to construct .
In general reduce the base first, . For , initialize and process the remaining binary digits with , followed, for a digit one, by . The loop invariant is
where is the processed prefix value. The congruence is preserved because modular arithmetic respects multiplication: if , then and . Thus changing representatives never changes the final congruence class.
Both factors in every product are less than , so the unreduced product is less than , and the stored result is again less than . The same bounds hold for a gigantic exponent, such as : there are squarings, each on bounded-size residues. For base two, the corresponding ordinary power would have binary digits. The benefit is avoiding the huge ordinary power altogether, rather than constructing it and taking one final remainder. Initial reduction is essential when the supplied base is much larger than the modulus.
For , return under the same empty-product convention as exponentiation by squaring. For , require , find the modular multiplicative inverse , and compute ; the extended Euclidean algorithm can find that inverse. Its cost is separate from the positive-exponent binary powering multiplication count. For example, , while is undefined because and are not coprime.
Use exponentiation by squaring with the remaining exponent halved on every iteration:
def eaFast(n: Int): Double = {
  require(n > 0)
  var remaining = n
  var base = 1.0 + 1.0 / n.toDouble
  var result = 1.0
  while (remaining > 0) {
    if (remaining % 2 == 1) result *= base
    base *= base
    remaining /= 2
  }
  result
}
Writing , the exact-arithmetic loop invariant is and . For an even integer exponent , replace the base by its square and the exponent by . For an odd integer exponent , first multiply the accumulator by the base and then make the same replacement. Both preserve the product. The loop variant is remaining, which strictly decreases while positive. At exit the remaining exponent is zero, so the returned value approximates .
There are iterations, squarings and one accumulator multiplication for each set bit of : between and multiplications. Thus the bound is as , or including the small case . All power variables are Double; no unintended Int squaring occurs.
The algorithmic intention is exponentiation by squaring to compute for . With exact arithmetic, its loop invariant is
Initially result = 1, y = x, and i = n. For an even integer , squaring y and replacing i by preserves the product. For an odd integer , first multiply result by y; then . The nonnegative loop variant i decreases by halving whenever positive. At exit , so the loop invariant yields result = x^n. There are multiplication steps.
Two qualifications are essential for the actual source. There is no requirement that n be nonnegative: for every n <= 0 the printed function simply returns 1.0. Also, var y = x infers Int, so y *= y uses wrapping integer arithmetic, while the accumulator uses floating-point arithmetic. For example, anotherfunc(50000, 2L) returns -1794967296.0, rather than 2500000000.0. An exact-power loop invariant cannot prove a false claim about that execution.
More precisely, for positive n, after iterations the remaining exponent is , and the Int base is the signed 32-bit representative of modulo . The accumulator multiplies those signed representatives for the set bits of n, in increasing bit order, with a floating-point rounding after each multiplication. This describes the actual code even when the intended power law fails. In an exact implementation, use a nonnegative-exponent precondition and arbitrary-precision integers, for example:
def powerExact(x: Int, n: Long): BigInt = {
  require(x > 0 && n >= 0)
  var result = BigInt(1)
  var y = BigInt(x)
  var i = n
  while (i > 0) {
    if (i % 2 == 1) result *= y
    y *= y
    i /= 2
  }
  result
}
The displayed loop invariant applies exactly to this version. It performs logarithmically many arbitrary-precision multiplications; their bit cost grows with operand size, so that statement is not an bit-complexity bound. Merely making the accumulator a Double does not widen the separate Int base variable.
Pépin's test 2026-10-14
For , Pépin's test says that the Fermat number is a prime number exactly when the displayed modular congruence holds. Modular exponentiation evaluates it by exponentiation by squaring without constructing the enormous ordinary power. The index restriction excludes , where the base itself is divisible by the candidate.[ref]
For a proof outline of sufficiency, any prime factor of a passing candidate gives multiplicative order exactly , a power of two: its half-power is , rather than . Fermat's little theorem forces , so , and hence . Conversely, for a prime candidate, ; quadratic reciprocity and Euler's criterion give the required half-power. At , the check is .
Recursion invariant 2026-10-24
A relationship between a recursive procedure's arguments, accumulated state and original input that holds at every reachable recursive call. For accumulator-based exponentiation by squaring, is a recursion invariant under exact arithmetic. The base case converts it into the desired result, while the recursive step and a decreasing argument justify preservation and termination.