Skip to content

Commit 9a8e7de

Browse files
kostoglscclauss
andcommitted
Adding Armstrong number (TheAlgorithms#1708)
* Adding Armstrong number * Update armstrong_numbers * Update armstrong_numbers.py * Update armstrong_numbers.py * Update armstrong_numbers.py Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent 724b7d2 commit 9a8e7de

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

maths/armstrong_numbers.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
"""
2+
An Armstrong number is a number that is equal to the sum of the cubes of its digits.
3+
For example, 370 is an Armstrong number because 3*3*3 + 7*7*7 + 0*0*0 = 370.
4+
An Armstrong number is often called Narcissistic number.
5+
"""
6+
7+
8+
def armstrong_number(n: int) -> bool:
9+
"""
10+
This function checks if a number is Armstrong or not.
11+
12+
>>> armstrong_number(153)
13+
True
14+
>>> armstrong_number(200)
15+
False
16+
>>> armstrong_number(1634)
17+
True
18+
>>> armstrong_number(0)
19+
False
20+
>>> armstrong_number(-1)
21+
False
22+
>>> armstrong_number(1.2)
23+
False
24+
"""
25+
if not isinstance(n, int) or n < 1:
26+
return False
27+
28+
# Initialization of sum and number of digits.
29+
sum = 0
30+
number_of_digits = 0
31+
temp = n
32+
# Calculation of digits of the number
33+
while temp > 0:
34+
number_of_digits += 1
35+
temp //= 10
36+
# Dividing number into separate digits and find Armstrong number
37+
temp = n
38+
while temp > 0:
39+
rem = temp % 10
40+
sum += (rem ** number_of_digits)
41+
temp //= 10
42+
return n == sum
43+
44+
45+
# In main function user inputs a number to find out if it's an Armstrong or not. Th function armstrong_number is called.
46+
def main():
47+
num = int(input("Enter an integer number to check if it is Armstrong or not: ").strip())
48+
print(f"{num} is {'' if armstrong_number(num) else 'not '}an Armstrong number.")
49+
50+
51+
if __name__ == '__main__':
52+
import doctest
53+
54+
doctest.testmod()
55+
main()

0 commit comments

Comments
 (0)