Skip to content

Instantly share code, notes, and snippets.

@datalifenyc
Last active April 7, 2024 01:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save datalifenyc/112fb0feecb2ee6da66aec2326c36d47 to your computer and use it in GitHub Desktop.
Save datalifenyc/112fb0feecb2ee6da66aec2326c36d47 to your computer and use it in GitHub Desktop.
Return True if the nth root of an number is an integer.
"""
Stack Overflow: Is cube root integer?
https://stackoverflow.com/a/50666516/3857372
"""
# Import `math` module.
import math
# Define `is_integer`
def is_integer(num: float, root: float) -> bool:
"""Return True if the nth root of an number is an integer.
Args:
num (float): number to evaluate if it has an integer for the nth root
root (float): nth root to evaluate the number against
Returns:
bool: `True` if the nth root of an integer is a whole number
"""
try:
# Calculate the nth root of an integer
nth_root = num**(1/root)
print(f'\nThe {root} root of {num} is ~{nth_root}.')
# Calculate the nearest whole number
nearest_whole_number = round(nth_root)
print(f'The nearest whole number to {nth_root} is {nearest_whole_number}')
# Check if the nth root is close (default: 1e-09) to the nearest whole number
is_whole_number = math.isclose(nth_root, nearest_whole_number)
print(f'Is the {root} root of {num} close to a whole number? {is_whole_number}')
return is_whole_number
except Exception as e:
print(f'Review Error: {e}')
return False
# Call `is_integer` with (2**17)**3 and 3 as arguments
if __name__ == '__main__':
num = eval(input('Enter a number: ')) # e.g., (2**17)**3 for number
root = eval(input('Enter a root: ')) # e.g., 3 for root
print(is_integer(num, root))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment