Potentiation is nothing more than multiple multiplication operations, so you can implement multiplication through sums and use it for potentiation. Luckily this has already been discussed here in the community:
It is worth noting that in order to be possible this type of operation the two operands will need to be integer, because the multiplication A*B by sum is nothing more than the number A summed B times (or the number B summed A times) and the potentiation is the analogous form, with the multiplication operation: A times B (or B times A).
Also, assuming that the idea is not to use the multiplication operator also we can not use the division operator; thus potentiation with negative exponents will not be possible, since the negative exponent is nothing more than a representation of the fraction of the inverted base, which would generate a division operation.
Also, there are no limitations regarding the base signal, which can be both positive and negative. Thus:
def multiply(a, b):
result = sum(b for _ in range(abs(a)))
return result if a > 0 else -result
def pow(base, exponent):
result = 1
for _ in range(exponent):
result = multiply(result, base)
return result
For testing:
tests = [
(2, 3), # Base positiva
(-3, 5), # Base negativa
(1, 99), # Base igual a um
(0, 2), # Base igual a zero
(5, 0), # Expoente igual a zero
]
for base, exponent in tests:
assert pow(base, exponent) == base**exponent, \
f"{pow(base, exponent)} é diferente de {base**exponent}"
See working on Repl.it
As no output is produced when performing, all conditions in assert
have been validated, which shows that the function return pow
was the same as the native operator of the language.
How this code behaves when one or more entries are negative?
– Woss
Pow in Python: https://www.geeksforgeeks.org/pow-in-python/
– Maury Developer
@Anderson, the same way it behaves if the multiplier is negative: it doesn’t work. The original code had no error handling, and honestly, I don’t think you need to worry about it in a code that will never be used seriously in production.
– Andre