MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / actual_power

Function actual_power

divide_and_conquer/power.py:1–27  ·  view source on GitHub ↗

Function using divide and conquer to calculate a^b. It only works for integer a,b. :param a: The base of the power operation, an integer. :param b: The exponent of the power operation, a non-negative integer. :return: The result of a^b. Examples: >>> actual_power(3, 2)

(a: int, b: int)

Source from the content-addressed store, hash-verified

1def actual_power(a: int, b: int) -> int:
2 """
3 Function using divide and conquer to calculate a^b.
4 It only works for integer a,b.
5
6 :param a: The base of the power operation, an integer.
7 :param b: The exponent of the power operation, a non-negative integer.
8 :return: The result of a^b.
9
10 Examples:
11 >>> actual_power(3, 2)
12 9
13 >>> actual_power(5, 3)
14 125
15 >>> actual_power(2, 5)
16 32
17 >>> actual_power(7, 0)
18 1
19 """
20 if b == 0:
21 return 1
22 half = actual_power(a, b // 2)
23
24 if (b % 2) == 0:
25 return half * half
26 else:
27 return a * half * half
28
29
30def power(a: int, b: int) -> float:

Callers 1

powerFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected