Python Practice Example 13
Problem:Print all "Narcissistic numbers". A "Narcissistic number" is a three-digit number whose sum of the cubes of its digits equals the number itself. For example: 153 is a "Narcissistic number" because 153 = 1 cubed + 5 cubed + 3 cubed.
Program analysis:Use a for loop to control numbers from 100 to 999, decompose each number into units, tens, and hundreds digits.
Program source code:
Example (Python 2.0+)
#!/usr/bin/python
# -*- coding: UTF-8 -*-
for n in range(100,1000):
i = n / 100
j = n / 10 % 10
k = n % 10
if n == i ** 3 + j ** 3 + k ** 3:
print n
Example (Python 3.0+)
for n in range(100,1000):
i = n // 100
j = n // 10 % 10
k = n % 10
if n == i*i*i + j*j*j + k*k*k:
print(n)
The output of the above example is:
153 370 371 407Other extensions
Python 100 Examples