Check if a number is Peterson number in Python

In this tutorial, we are going to learn how to check if a number is a Peterson number or not using Python.

But first, what is a Peterson number? Peterson number is that number whose sum of factorials of each digit of the number is equal to the number itself. Let me help you understand better with an example:

Let us take the number 145 :

So 145 has the digits 1,4,5.
Now, 1!+4!+5!= 1+24+120 
             = 145 i.e the number itself.

So now that you understand what a Peterson number is, let’s dive into coding it on Python.

I will break this down into a 2 step process. First, we are gonna make a (user-defined) factorial function using recursion and then use it into our main Peterson function.

We are just going to make a simple factorial function using recursion (where a function calls itself)

def factorial(n):
 
    return 1 if (n==1 or n==0) else n * factorial(n - 1)

The Peterson Number Function using Recursion

So now that we are done with the factorial part, we can now shift our focus to the main Peterson function. I have made a brief list of things to be done in the function itself in a step-by-step manner :

  1. Initialize 2 variables, one will be the summation term used to sum the factorials of each digit of the number, set this variable to 0 initially, and the other to save to number itself so that we can check it with the sum later.
  2. Extract each digit from the number and add it’s factorial value to the summation variable created previously. This can be achieved by iterating over the number and taking modulo 10 for each step of the iteration.
  3. Check if the summation is equal to the variable itself or not and return the appropriate boolean.

Before you see the code, I highly recommend you to try and code it out yourself using the explanation above before having a look at the code.

Here goes the code:

def peterson_num (n): 
    # Initializing the variables
    num = n 
    sum_val = 0
    # Extracting the digits and adding their factorial values to sum_val
    while n > 0: 
        digit = int(n % 10) 
        sum_val += factorial(digit) 
        n = int(n / 10) 
    # Checking if the sum is equal to the num and returning boolean.
    return (sum_val == num)

Now, let’s call the function.

n=14
if peterson_num(n):
    print("Yes, {} is a Peterson Number".format(n))
else:
    print("No, {} is not a Peterson Number ".format(n))

Output:

Yes, 145 is a Peterson Number

Congratulations! Now you know what Peterson number is as well as code it up in Python.

 

Leave a Reply

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