Last active
July 20, 2018 10:57
-
-
Save carlos-menezes/be7decbea9fb40509181353b70b607cf to your computer and use it in GitHub Desktop.
Checks if a number is an Armstrong number.
This file contains 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
# An armstrong number is a number that is the sum of its own digits raised to the power of number of digits that make up the original number. | |
import sys | |
def is_armstrong(n): | |
n = int(n) | |
sum_result = 0 | |
# 1. Split the number into it's digits and store them in a list. | |
digits = list(str(n)) | |
# 2. Get length of the number. | |
digits_length = len(digits) | |
# 3. Convert the elements of the 'digits' list to integers in order to perform mathematical operations. | |
for iterator in range(len(digits)): | |
digits[iterator] = int(digits[iterator]) | |
# 4. Raise the digits to the power of digits_length, e.g: n = 653, then digits_length = 3, therefore 6^3 + 5^3 + 3^3. | |
for iterator in digits: | |
sum_result += iterator ** digits_length | |
# 5. Compare the result of the passed number and the sum_result. | |
# e.g: n = 371, digits_length = 3, 3^3 + 7^3 + 1^3 = 371. 371 = 371 => n == sum_result, therefore returning True. | |
if n == sum_result: | |
return True | |
# ... Taking the example above, with n = 653, 6^3 + 5^3 + 3^3 = 368. It'd not return True, because 653 != 368. Therefore, it would return False. | |
return False | |
# HOW TO RUN: $ py armstrongNumber.py n, where n is the number to check for... armstrongness. | |
if __name__ == "__main__: | |
print(is_armstrong(sys.argv[1])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment