# Algorithm Part 1: Checking for Narcissism in Numbers (Python)

Algorithm Part 1: Checking for Narcissism in Numbers (Python)

Basically, a narcissistic number is a number that is the sum of its own digits each raised to the power of the number of digits it has.

P.S: They are also referred to as Armstrong numbers. Like 💪🏽 (Just kidding. 😉 ) These special numbers are actually named after Michael Armstrong who discovered them.

So, for example:

153 is a narcissistic number, how do we know? Let’s do the Math. 1^3+5^3+3^3

=1+125+27

=153.

The numbers could get pretty large though. 8208, 92727, 93084…are all narcissistic.

Of course not all numbers are narcissistic. So how do you know if a number is narcissistic or not without having to do all that Math yeah? Especially since the numbers can get cumbersome.

Let’s code that!

Oh wait, it’s a better idea to figure out the algorithm first before jumping into code. Yup! this actually makes the task a lot clearer.

And too, makes it easier to break down the coding tasks which makes for organisation. It also serves as a useful guide if you need to rework the solution later on.

So, let’s just say your Algorithm is pretty much like the recipe. With it, you get a clearer picture of what aspects of a language you’ll use.

ALGORITHM FOR FINDING NARCISSISTIC NUMBERS

1. Determine the length of n-digits in the number and store it in a variable that could be called power.
2. Loop through the number
3. Raise each digit to the power.
4. Sum the result of the operation.
5. Compare the result with the original number.
6. If the final result equals the original number, then the number is narcissistic.
7. Else, if the final result does not equal the original number, it is not narcissistic.
8. Output a response.

With this in mind, we could now code the solution.

So actually, this solution is in 2 parts: Python and JavaScript. The second part of this series is the JavaScript version which would be published in my next post.

NARCISSISTIC NUMBERS: PYTHON

In Step 1, a list container total is created for storing the sum of the operation. Len() is an operation that can only work with strings according to the Python documentation so the value received needs to be converted to a string datatype to find the length. However, in order to perform further operations, it is converted back to integer and stored in a variable power.

In Step 2, we loop through the value inputted by the user. Take note that the value is converted to a string in order to separate each digit of the number. If not converted first to string, Python tells you something like: “ int object not iterable,” which means you cannot loop through an integer object.

After getting each digit of the number, we need to convert them back to integer and store in digits. 