Generic implementation of powering#

This implements powering of arbitrary objects using a square-and-multiply algorithm.

sage.arith.power.generic_power(a, n)[source]#

Return \(a^n\).

If \(n\) is negative, return \((1/a)^{-n}\).

INPUT:

  • a – any object supporting multiplication (and division if n < 0)

  • n – any integer (in the duck typing sense)

EXAMPLES:

sage: from sage.arith.power import generic_power
sage: generic_power(int(12), int(0))
1
sage: generic_power(int(0), int(100))
0
sage: generic_power(Integer(10), Integer(0))
1
sage: generic_power(Integer(0), Integer(23))
0
sage: sum([generic_power(2,i) for i in range(17)]) #test all 4-bit combinations
131071
sage: F = Zmod(5)
sage: a = generic_power(F(2), 5); a
2
sage: a.parent() is F
True
sage: a = generic_power(F(1), 2)
sage: a.parent() is F
True

sage: generic_power(int(5), 0)
1
sage: generic_power(2, 5/4)
Traceback (most recent call last):
...
NotImplementedError: non-integral exponents not supported
>>> from sage.all import *
>>> from sage.arith.power import generic_power
>>> generic_power(int(Integer(12)), int(Integer(0)))
1
>>> generic_power(int(Integer(0)), int(Integer(100)))
0
>>> generic_power(Integer(Integer(10)), Integer(Integer(0)))
1
>>> generic_power(Integer(Integer(0)), Integer(Integer(23)))
0
>>> sum([generic_power(Integer(2),i) for i in range(Integer(17))]) #test all 4-bit combinations
131071
>>> F = Zmod(Integer(5))
>>> a = generic_power(F(Integer(2)), Integer(5)); a
2
>>> a.parent() is F
True
>>> a = generic_power(F(Integer(1)), Integer(2))
>>> a.parent() is F
True

>>> generic_power(int(Integer(5)), Integer(0))
1
>>> generic_power(Integer(2), Integer(5)/Integer(4))
Traceback (most recent call last):
...
NotImplementedError: non-integral exponents not supported
sage: class SymbolicMul(str):
....:     def __mul__(self, other):
....:         s = "({}*{})".format(self, other)
....:         return type(self)(s)
sage: x = SymbolicMul("x")
sage: print(generic_power(x, 7))
(((x*x)*(x*x))*((x*x)*x))
>>> from sage.all import *
>>> class SymbolicMul(str):
...     def __mul__(self, other):
...         s = "({}*{})".format(self, other)
...         return type(self)(s)
>>> x = SymbolicMul("x")
>>> print(generic_power(x, Integer(7)))
(((x*x)*(x*x))*((x*x)*x))