Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Armstrong Numbers

Python Armstrong Numbers

Document Object Reference Manual Python3 Examples

If an n -digit positive integer equals the sum of its digits each raised to the n power, the number is called an Armstrong number. For example 1^3 + 5^3 + 3^3 = 153.

Armstrong numbers below 1000: 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407.

The following code checks whether a number entered by the user is an Armstrong number:

Example (Python 3.0+)

Filename : test.py

author by : www.runoob.com

Python Check Whether a User-Entered Number Is an Armstrong Number

Get the number entered by the user

num

=

int

(

input

(

"

Please enter a number:

"

)

)

Initialize the variable sum

sum

=

0

Exponent

n

=

len

(

str

(

num

)

)

Detection

temp

=

num

while

temp

0

:

digit

=

temp

%

10

sum

+=

digit

**

n

temp

//=

10

Output result

if

num

==

sum

:

print

(

num

,

"

is an Armstrong number

"

)

else

:

print

(

num

,

"

is not an Armstrong number

"

)

The output of the code above is:


$ python3 test.py 
请输入一个数字: 345
345 不是阿姆斯特朗数

$ python3 test.py 
请输入一个数字: 153
153 是阿姆斯特朗数

$ python3 test.py 
请输入一个数字: 1634
1634 是阿姆斯特朗数

Get Armstrong numbers within a specified range

Example (Python 3.0+)

Filename :test.py

author by : www.runoob.com

Get the number entered by the user

lower

=

int

(

input

(

"

Minimum value:

"

)

)

upper

=

int

(

input

(

"

Maximum value:

"

)

)

for

num

in

range

(

lower

,

upper

1

)

:

Initialize sum

sum

=

0

Exponent

n

=

len

(

str

(

num

)

)

Detection

temp

=

num

while

temp

0

:

digit

=

temp

%

10

sum

+=

digit

**

n

temp

//=

10

if

num

==

sum

:

print

(

num

)

The output of the code above is:


最小值: 1
最大值: 10000
1
2
3
4
5
6
7
8
9
153
370
371
407
1634
8208
9474

In the example above we printed the Armstrong numbers between 1 and 10000.

Document Object Reference Manual Python3 Examples