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

Function binary_exp_recursive

maths/binary_exponentiation.py:17–50  ·  view source on GitHub ↗

Computes a^b recursively, where a is the base and b is the exponent >>> binary_exp_recursive(3, 5) 243 >>> binary_exp_recursive(11, 13) 34522712143931 >>> binary_exp_recursive(-1, 3) -1 >>> binary_exp_recursive(0, 5) 0 >>> binary_exp_recursive(3, 1) 3

(base: float, exponent: int)

Source from the content-addressed store, hash-verified

15
16
17def binary_exp_recursive(base: float, exponent: int) -> float:
18 """
19 Computes a^b recursively, where a is the base and b is the exponent
20
21 >>> binary_exp_recursive(3, 5)
22 243
23 >>> binary_exp_recursive(11, 13)
24 34522712143931
25 >>> binary_exp_recursive(-1, 3)
26 -1
27 >>> binary_exp_recursive(0, 5)
28 0
29 >>> binary_exp_recursive(3, 1)
30 3
31 >>> binary_exp_recursive(3, 0)
32 1
33 >>> binary_exp_recursive(1.5, 4)
34 5.0625
35 >>> binary_exp_recursive(3, -1)
36 Traceback (most recent call last):
37 ...
38 ValueError: Exponent must be a non-negative integer
39 """
40 if exponent < 0:
41 raise ValueError("Exponent must be a non-negative integer")
42
43 if exponent == 0:
44 return 1
45
46 if exponent % 2 == 1:
47 return binary_exp_recursive(base, exponent - 1) * base
48
49 b = binary_exp_recursive(base, exponent // 2)
50 return b * b
51
52
53def binary_exp_iterative(base: float, exponent: int) -> float:

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected