#!/usr/bin/python3 # -*- coding: utf-8 -*- """ Exponentiation """ print(2 ** 8) # %% Loop def exp_loop(b: int, n: int) -> int: result = 1 for c in range(n): result *= b print("c=", c, "and result=", result) return result for n in range(1, 17): val = exp_loop(2, n) print("2 to the ", n, "is ", val, "\n") # %% What is the b^-n? def exp_loop_neg_rec(b: int, n: int) -> float: result = 1 if 0 <= n: for c in range(n): result *= b print("c=", c, "and result=", result) return result else: return 1 / exp_loop_neg_rec(b, -n) for n in range(-1, -17, -1): val_float = exp_loop_neg_rec(2, n) print("2 to the ", n, "is ", val_float, "\n") # %% Inefficient recursive exponentiation def exp_rec(b: int, n: int) -> int: """ Calculates b^n for positive n integers """ print("Calling with b =", b, "and n=", n) if n == 0: return 1 else: return b * exp_rec(b, n - 1) for n in range(1, 17): val = exp_rec(2, n) print("2 to the ", n, "is ", val, "\n") # %% Efficient recursive exponentiation def exp_rec_eff(b: int, n: int) -> int: """ Efficiently calculates b^n for positive n integers """ print("Calling with b =", b, "and n=", n) if n == 1: return b elif (n & 1) == 0: return exp_rec_eff(b * b, n // 2) else: return exp_rec_eff(b * b, n // 2) * b for n in range(1, 17): val = exp_rec_eff(2, n) print("2 to the ", n, "is ", val, "\n")