Last active
April 7, 2024 01:54
-
-
Save datalifenyc/112fb0feecb2ee6da66aec2326c36d47 to your computer and use it in GitHub Desktop.
Return True if the nth root of an number is an integer.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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