Advertisement
banovski

Exponentiation

Nov 10th, 2022 (edited)
248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.91 KB | Source Code | 0 0
  1. #! /usr/bin/env python3
  2.  
  3. def native_power_fuction(number, exponent):
  4.     return pow(number, exponent)
  5.  
  6. # pow(1000000, 100000)
  7. # 4 function calls in 0.295 seconds
  8.  
  9. def native_power_operator(number, exponent):
  10.     return number ** exponent
  11.  
  12. # native_power_operator(1000000, 100000)
  13. # 4 function calls in 0.295 seconds
  14.  
  15. def power_one(number, exponent):
  16.     accumulator = 1
  17.     while exponent > 0:
  18.         accumulator *= number
  19.         exponent -= 1
  20.     return accumulator
  21.  
  22. # power_one(1000000, 100000)
  23. # 4 function calls in 11.608 seconds
  24.  
  25. def power_two(number, exponent):
  26.     accumulator = 1
  27.     for current_exponent in range(exponent, 0, -1):
  28.         accumulator *= number
  29.     return accumulator
  30.  
  31. # power_two(1000000, 100000)
  32. # 4 function calls in 11.576 seconds
  33.  
  34. def get_binary_power(source_number, exponent):
  35.     result = 1
  36.     n_exponent = exponent
  37.     a_source = source_number
  38.  
  39.     while n_exponent != 0:
  40.         # if not "{0:b}".format(n_exponent).endswith("0"):
  41.         # if not str(bin(n_exponent)).endswith("0"):
  42.         # if not n_exponent % 2 == 0:
  43.         if not str(n_exponent).endswith(("0", "2", "4", "6", "8")):
  44.             result *= a_source
  45.         n_exponent >>= 1
  46.         a_source *= a_source
  47.     return result
  48.  
  49. # get_binary_power(1000000, 100000)
  50. # with the format method: 38 function calls in 0.664 seconds
  51. # with str and bin functions: 38 function calls in 0.667 seconds
  52. # with modulo: 4 function calls in 0.664 seconds
  53. # with str and endswith: 21 function calls in 0.664 seconds
  54.  
  55. def get_mod_binary_power(source_number, exponent):
  56.     if exponent == 0:
  57.         return 1
  58.  
  59.     if exponent % 2 == 1:
  60.         return get_mod_binary_power(source_number, exponent - 1) * source_number
  61.  
  62.     result = get_mod_binary_power(source_number, exponent // 2)
  63.  
  64.     return result * result
  65.  
  66. # get_mod_binary_power(1000000, 100000)
  67. # 26 function calls (4 primitive calls) in 0.295 seconds
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement