Back

Strong Number in Python

28 Jan 2025
4 min read

A strong number in Python is a concept that arises from number theory. A strong number, also known as a Krishnamurthy number or Factorion is defined as a number that is equal to the sum of the factorials of its digits. 

In this article, we will discuss the basics of strong numbers in Python, explain how factorials are calculated, and show how to identify a strong number. We will also provide Python code for strong number detection.

What is a Strong Number?

In simpler terms, a strong number is a number whose value equals the sum of the factorials of its digits. When you break down the number and calculate the factorial of each digit, and if their sum equals the original number then that number is called strong.

Factorial of a number 

The factorial of a non-negative number n is written as n!x resulting from multiplying all positive whole numbers from 1 up to nnn. The formula is: n!=n×(n−1)×(n−2)×⋯×2×1.

When n=0, the factorial is 1, so 0!=1. Factorials are used in math and statistics mainly in problems involving permutations and combinations.

Before learning into code, it's essential to understand factorials. The factorial of a non-negative integer n is denoted as n! and the result of multiplying all positive integers less than or equal to n.

example:

0!=1

1!=1

2!=2×1=2

3!=3×2×1=6

4!=4×3×2×1=24

Factorials grow exponentially, so calculating factorials is important for larger values.

Strong Number Examples 

  1.  40585

Now, take an example of the number 40585 and check if it's a strong number by following the same process.

The digits of 40585 are 4, 0, 5, 8, and 5. To calculate the factorial of each digit, we find that the factorial of 4 is 4!=24, the factorial of 0 is 0!=1 (as 0! is defined as 1), the factorial of 5 is 5!=120, and the factorial of 8 is 8!=8×7×6×5×4×3×2×1=40320. 

Another occurrence of 5 also has a factorial of 5!=120. Summing up these factorials gives 4!+0!+5!+8!+5!=24+1+120+40320+120=405854! + 0! + 5! + 8! + 5! = 24 + 1 + 120 + 40320 + 120 = 40585. Finally, we observe that the sum of these factorials (40585) is equal to the original number (40585).

Since the sum of the factorials of the digits equals the original number, 40585 is a strong number.

This number is known as a Krishnamurthy number or a factorion, which is a special case of strong numbers.

  1. 145

To check if 145 is a strong number, we check if it equals the sum of the factorials of its digits. The digits of 145 are 1, 4, and 5. 

The factorial of 1 is 1!=1, the factorial of 4 is 4!=4×3×2×1=24, and the factorial of 5 is 5!=5×4×3×2×1=120. When we Sum these give 1+24+120=145. Since the sum of the factorials equals the original number, 145 is a strong number.

Non-strong Number Example 3

  1. 123 

Now consider the number 123 to illustrate a non-strong number.

The numbers in 123 are 1, 2, and 3. To calculate the factorial of each digit, we have to find the factorial of 1 which is 1!=1, the factorial of 2 is 2!=2×1=2, and the factorial of 3 is 3!=3×2×1=6. When we sum up the factorials of these digits, it should be 1!+2!+3!=1+2+6=9. 

Finally, we compare the sum of the factorials (9) to the original number (123). Since 9 is not equal to 123, it is clear that 123 is not a strong number.

Steps for Checking Number is Strong or Not

Here are step-by-step processes to check if a number is a Strong Number or not.

1. Input the Number

Ask the user to enter a number. This is the number we'll check to see if it's a Strong Number. Once entered, store the number in a variable for processing.

2. Set Up Variables

Create a variable to hold the sum of the factorials of the digits. Keep the original number in another variable for later comparison, which helps us check if the sum of the factorials equals the original number.

3. Extract the Digits

Use a loop to check each digit of the number. You can do this by taking the last digit with modulus and removing it from the number using integer division. Repeat this for every digit of the number.

4. Calculate Factorials

For each digit, calculate its factorial. You can use Python's built-in math.factorial() function or write your own method to calculate the factorial. Add all the factorials for each digit.

5. Check the Sum

After calculating the factorials of all the digits, add them up. If the total matches the original number, it is a Strong Number. Otherwise, it’s not.

6. Display the Result

Finally, output whether the number is a Strong Number or not based on your comparison in the previous step. If the sum matches, it’s a strong number; if not, it isn’t.

Python Code for Strong Number

There are multiple ways to programmatically approach a Python program for strong number problems. Here are some methods that are used to check if a number is a strong number, such as using a while loop, for loop, and the math module in Python.

custom img

Method 1: Using a While Loop

In this approach, we use a while loop to extract each digit from the number, calculate the factorial of each digit, and sum them. A number is considered a strong number if the sum factorial of each digits equals the original number.

Code:

def is_strong_number(num):
    sum_of_factorials = 0
    original_num = num
    while num > 0:
        digit = num % 10  #This Excerpt the last digit
        factorial = 1
        for i in range(1, digit + 1):  # Calculate the factorial of the digit
            factorial *= i
        sum_of_factorials += factorial  # This can sum the factorials
        num //= 10  # Remove last digit 
    return sum_of_factorials == original_num  # Compare with the original number

# Example usage
number = int(input("Enter a number: "))
if is_strong_number(number):
    print(f"{number} is a Strong Number.")
else:
    print(f"{number} is not a Strong Number.")

Explanation of the Code:

The code determines whether a number is a Strong Number, which is defined as a number where the sum of the factorials of its digits is equal to the number itself.

  • The function is_strong_number(num) takes an integer input and calculates the factorial of each digit using a while loop.
  • The digits are extracted using modulus (%) and integer division (//). Each factorial is calculated using a for loop and added to a running total (sum_of_factorials).
  • Once all digits are processed, the sum of the factorials is compared to the original number. If they match, the function returns True; otherwise, it returns False.

After the function is called the program prints whether the number is a Strong Number based on the comparison.

Example and Output

For input 123, the factorials are:

  • 1!=1
  • 2!=2
  • 3!=6

Sum: 1+2+6=91 + 2 + 6 = 91+2+6=9

Since 9 ≠ 123, the output is:

123 is not a Strong Number.

For input 145, the factorials are:

  • 1!=1
  • 4!=4×3×2×1=24
  • 5!=5×4×3×2×1=120

Sum: 1+24+120=145

Since 145=145, the output is:

145 is a Strong Number.

Method 2: Using For Loop

This Python strong number program is similar except it uses a for loop. We can split the number into digits using str() and loop through each character to compute the factorial of that digit.

Code:

def factorial(n):
    result = 1
    for i in range(1, n + 1):  # Calculate the factorial
        result *= i
    return result

def is_strong_number(num):
    sum_of_factorials = 0
    original_num = num

    for digit in str(num):
        sum_of_factorials += factorial(int(digit))  # Add the factorial of each digit

    return sum_of_factorials == original_num  # Check if the sum matches the original number

# Example usage
number = int(input("Enter a number: "))  # Take input from the user
if is_strong_number(number):
    print(f"{number} is a Strong Number.")
else:
    print(f"{number} is not a Strong Number.")

Explanation of the Code:

This is a clear explanation of the Python program for strong number code to help you understand it easily. 

1. Factorial Function:
The factorial(n) function calculates the factorial of a number n. It initializes a variable result to 1 and multiplies it by each number in the range from 1 to n. This process restarts through a loop, and the final result is the factorial of n.

2. User Input and Output:
The program starts the user to enter a number. It then calls the is_strong_number() function with the user's input. If the function returns True, the program prints that the number is a Strong Number. Otherwise, it prints that the number is not.

Example (40585) and Output:

For 40585, the factorials of the digits (4, 0, 5, 8, 5) are calculated:

  • 4!=24, 0!=1, 5!=120, 8!=40320,and 5!=120.
  • The sum is 24+1+120+40320+120=40585 - matching the original number.
Enter a number: 40585 
40585 is a Strong Number.

Method 3: Using Python's Built-in Math Module

Python’s built-in math.factorial() function is a useful tool to calculate the factorial of a number more efficiently.

Code:

import math

def is_strong_number(num):
    sum_of_factorials = sum(math.factorial(int(digit)) for digit in str(num)) # It sums the factorials
    return sum_of_factorials == num  # Check the sum against the original number


# Example usage

number = int(input("Enter any number: "))  # Input: 145
if is_strong_number(number):
    print(f"{number} is a Strong Number.")
else:
    print(f"{number} is not a Strong Number.")

Explanation of the Code:

Here is a simple explanation of the Python program for checking strong numbers.

1. Import the Math Module

The code starts by importing Python's math library, which is used to calculate the factorial of a number.

2. Define the (is_strong_number) Function

This function takes an integer as input and calculates the sum of the factorials of its digits. It compares the sum to the original number to determine if it is a Strong Number.

3. Input from the User

The code asks the user to input a number. For example, the user could enter 145. This input is converted to an integer for further processing.

4. Check if the Number is a Strong Number

Using the is_strong_number function, the sum of factorials of the digits is calculated. If the sum matches the original number, it prints that the number is a Strong Number. Otherwise, it informs the user that it’s not a Strong Number.

Output:

Enter any number: 145
145 is a Strong Number.
Enter any number: 123
123 is not a Strong Number.

For 145, the sum of the factorials equals the number, so the output will be that 145 is a Strong Number. For 123, the sum of factorials is different from the number, so it will output that it is not a Strong Number.

Method 4: Python Program to Check for Strong Number Using Recursion

The recursion method helps to calculate the factorial of each digit. It simplifies the logic for factorial computation so that the program is refined and clear.

Code:

# Function to calculate factorial using recursion
def factorial(n):
    if n == 0 or n == 1:  # Base case
        return 1
    return n * factorial(n - 1)  # Recursive calculation

# Function to check if a number is a Strong Number
def is_strong_number(num):
    original_num = num
    sum_of_factorials = 0

    for digit in str(num):  # Loop through each digit of the number
        sum_of_factorials += factorial(int(digit))  # Add factorial of digit to the sum

    return sum_of_factorials == original_num  # Compare sum with the original number

# Example usage
number = int(input("Enter a number: "))  # User input
if is_strong_number(number):
    print(f"{number} is a Strong Number.")
else:
    print(f"{number} is not a Strong Number.")

Explanation of the Code:

Here is a simple and detailed explanation to check for a strong number using recursion.

1. Factorial Function

The factorial function uses recursion to calculate the factorial of a number. If the number is 0 or 1, it returns 1. For other numbers, it multiplies the number by the factorial of n-1 and repeats until it reaches 1.

2. User Interaction

The program accepts an input number from the user and checks if it’s a Strong Number using the is_strong_number function and then displays whether the number is a Strong Number or not.

Example and Output

For input 145, the factorials are:

  • 1!=1
  • 4!=24
  • 5!=120

The sum of factorials: 1+24+120=145

Output

Enter a number: 145
145 is a Strong Number.

Example and Output

For input 123, the factorials are:

  • 1!=1
  • 2!=2
  • 3!=6

The sum of factorials: 1+2+6=9

Output:

Enter a number: 123
123 is not a Strong Number.

Method 5: Using Simple Iteration

In this method, we calculate the factorials of the digits from 0 to 9 once store them in a list, and then use this list to quickly check if a number is a strong number. This method is more efficient because we avoid recalculating the factorials for each digit frequently.

Code:

# Precompute the factorials for digits 0 to 9
factorials = [1, 1]  # Initial factorial values for 0! and 1!
for i in range(2, 10):  # Compute factorials for digits 2 through 9
    factorials.append(factorials[i-1] * i)

def is_strong_number(num):
    sum_of_factorials = 0  # To store the sum of the factorials of each digit

    # Loop through each digit of the number
    for digit in str(num):
        # Add the factorial of the digit to the sum
        sum_of_factorials += factorials[int(digit)]
    
    # Check if the sum of factorials equals the original number
    return sum_of_factorials == num

# Example usage
number = int(input("Enter a number: "))
if is_strong_number(number):
    print(f"{number} is a Strong Number.")
else:
    print(f"{number} is not a Strong Number.")

Explanation of the Code:

Here is a simple explanation of how to check for a strong number using Simple Iteration.

1. Precomputing Factorials

We create a list called factorials, where each index means the factorial of the connected digit. We manually set the factorial of 0 and 1 as 1, since both are equal to 1. After that, we calculate the factorial for each digit from 2 to 9 and store them in the list.

2. Checking for Strong Number

We first convert the number into a string so that we can easily access each digit. Then, for each digit, we check its precomputed factorial in the factorials list then we add all the factorials together and compare the sum to the original number.

3. Result

If the sum of the factorials is the same as the original number then it is a strong number. If the sum does not match, it's not a strong number.

Example and Output

For input 145:

Enter a number: 145
145 is a Strong Number.

For input 123:

Enter a number: 123
123 is not a Strong Number.

Find Strong Number in a List of Numbers

To find a strong number from the list of numbers, we will use list comprehension to find strong numbers in a list of numbers. List comprehension is a Python that allows us to create lists in a packed and readable way. 

We will check each number in the list to see if it is a strong number and then we will create a new list containing only the strong numbers.

import math

def is_strong_number(num):
    sum_of_factorials = sum(math.factorial(int(digit)) for digit in str(num))
    return sum_of_factorials == num

# List of numbers to check
numbers_list = [1, 2, 3, 145, 40585, 10, 123, 5]

# Use list comprehension to find strong numbers
strong_numbers = [num for num in numbers_list if is_strong_number(num)]

# Output the result
print("Strong numbers in the list:", strong_numbers)

Explanation of the Code:

Here is the explanation of this code that help you to understand this code easily.

1. is_strong_number(num) function checks whether a number is a strong number. It calculates the sum of the factorials of each of its digits and checks if the sum equals the number itself.

2. If the sum of the factorials is the same as the original number then it is a strong number. If the sum does not match then it's not a strong number.

Example and Output

Consider this list of numbers: [1, 2, 3, 145, 40585, 10, 123, 5].

  • 1 is a strong number because 1!=1.
  • 2 is a strong number because 2!=2.
  • 145 is a strong number because 1!+4!+5!=145.
  • 40585 is a strong number because 4!+0!+5!+8!+5!=40585.
  • Numbers like 3, 10, 123, and 5 are not strong numbers.

The output of this program will be:

Strong numbers in the list: [1, 2, 145, 40585]

Conclusion

A strong number program in Python is a number where the sum of the factorials of its digits is equal to the number. To check strong numbers in Python using loops and math.factorial function for efficiency.

With Python, you can easily detect strong numbers, even for larger values. Understanding strong numbers boosts both your math and Python skills and makes this concept easier to implement and explore.

Frequently Asked Questions

1. How can I check if a number is a Strong Number in Python?

To check if a number is a Strong Number, you first need to check if the number is down to its digits. Then, calculate the factorial of each digit and sum them up. Finally, compare the sum with the original number. If the sum matches the number itself, then it is a Strong Number. 

2. What Python functions can I use to calculate factorials?

In Python, the easiest way to calculate factorials is to use math.factorial() function from the built-in math module. This function is fast and efficient for calculating the factorial of a given number.

3. Are there any known Strong Numbers?

Yes, some strong numbers include 1, 2, 145, and 40585. These numbers are unique because they satisfy the condition where the sum of the factorials of their digits equals the number itself. 

4. What is a strong number between 1 and 1000?

The strong numbers between 1 and 1000 are 1, 2, and 145 because the sum of the factorials of their digits equals the number itself: 1! = 1, 2! = 2, and 1! + 4! + 5! = 145.

5. How do I find all Strong Numbers in a list using Python?

you can loop through each number in the list and check if it is a strong number using any method. Also, you can use a list or a simple loop to apply the strong number check and then return or print the numbers that fulfill the condition.

6. What are some common mistakes when checking for Strong Numbers?

Some common mistakes include forgetting to correctly handle single-digit numbers and forgetting that 0! equals 1. It's easy to manage the importance of converting each digit back to an integer before calculating its factorial. 

7. Is there an efficient way to compute factorials for checking Strong Numbers?

Yes, to improve efficiency when checking multiple Strong Numbers, you can precompute the factorials for digits 0-9 and store them in a list or dictionary. This reduces the need to recompute factorials every time, speeding up the process when working with large lists of numbers. This method optimizes the checking process by reusing previously calculated values.

Read More Articles

Chat with us
Chat with us
Talk to career expert