Skip to main content

How to check if a number is a strong number in Python

How to check if a number is a strong number in Python.

Here's a step-by-step tutorial on how to check if a number is a strong number in Python.

Prerequisites

Before we begin, make sure you have Python installed on your computer.

Understanding Strong Numbers

A strong number is a number whose sum of the factorial of its digits is equal to the number itself.

For example, let's take the number 145: 1! + 4! + 5! = 1 + 24 + 120 = 145

145 is a strong number because the sum of the factorial of its digits is equal to the number itself.

Let's proceed with the implementation.

Step 1: Define a Function to Calculate Factorial

First, we need to define a function that calculates the factorial of a given number. We'll use this function later to calculate the factorial of each digit in the given number.

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

Step 2: Define a Function to Check if a Number is Strong

Next, let's define a function that checks if a given number is strong or not. This function will use the factorial function defined in the previous step.

def is_strong_number(num):
# Convert the number to a string to access each digit
digits = str(num)

# Calculate the factorial of each digit and sum them up
digit_factorial_sum = sum(factorial(int(digit)) for digit in digits)

# Check if the sum is equal to the original number
if digit_factorial_sum == num:
return True
else:
return False

Step 3: Test the Function

Now, let's test our function with some sample inputs.

# Test the function with a strong number
print(is_strong_number(145)) # Output: True

# Test the function with a non-strong number
print(is_strong_number(123)) # Output: False

Step 4: Prompt User for Input

To make the program more interactive, we can prompt the user to enter a number and check if it is a strong number.

# Prompt the user to enter a number
num = int(input("Enter a number: "))

# Check if the entered number is a strong number
if is_strong_number(num):
print(f"{num} is a strong number.")
else:
print(f"{num} is not a strong number.")

Now, when you run the program, it will prompt you to enter a number. After entering the number, it will check if the number is a strong number and display the result accordingly.

That's it! You now have a step-by-step tutorial on how to check if a number is a strong number in Python.