PYTHON   51
closet powers
Guest on 26th August 2023 12:37:42 AM


  1. def closest_power(base, num):
  2.     '''
  3.    base: base of the exponential, integer > 1
  4.    num: number you want to be closest to, integer > 0
  5.    Find the integer exponent such that base**exponent is closest to num.
  6.    Note that the base**exponent may be either greater or smaller than num.
  7.    In case of a tie, return the smaller value.
  8.    Returns the exponent.
  9.    '''
  10.     # Your code here
  11.     result = 0
  12.     if base > num:
  13.         result = 0
  14.     elif base == num:
  15.         result = 1
  16.     else:
  17.         for i in range(1, int(num)):
  18.             if abs(base**i - num) <= abs(base**(i + 1) - num):
  19.                 result = i
  20.                 break
  21.     return result
  22.  
  23.  
  24. #print (closest_power(4,1))

Raw Paste

Login or Register to edit or fork this paste. It's free.