PYTHON: Find narcissistic number from 100 to 1000 by loop and if-statement

Spread the love

1. The definiation of narcissistic number

The narcissistic number is also called the pluperfect digital invariant (PPDI) or Armstrong number. A narcissistic number is an n-digit number(n>=3) whose sum of the n-th powers of the digits in each digit is equal to itself (eg: 1^3 + 5^3 + 3^3 =153).

2. Code Requirement

I would like to get the list of narcissistic numbers from 100 to 1000 and print it out.

Function name: narcissisticNum

Input parameter: from, end

Input:100, 1000

Ideal output: 153, 370, 371, 407

3. Code

def narcissisticNum(start, end):  # define narcissistic number
    for x in range(start, end):
        hundred_digit = x // 100  # hundred digits
        ten_digit = (x // 10) % 10  # ten digits
        one_digit = x % 10  # one digits
        num = hundred_digit ** 3 + ten_digit ** 3 + one_digit ** 3  # sum up
        if num == x:  #  condition
            print(num)

def main():
    print('********** Narcissistic number from 100 to 1000 **********')
    narcissisticNum(100, 1000)  # call narcissisticNum function

if __name__=="__main__":
    main()

4. Running Result

Zeren
If you want to know more about me, please get on the about page. :)
Posts created 18

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top
error: Content is protected !!