Strong Number in Python

Overview

A strong number in Python is a concept 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.

This article covers the basics of strong numbers in Python, explains how factorials are calculated, and demonstrates how to identify a strong number. Multiple Python implementation methods are provided with detailed code examples.

Article Metadata:

What is a Strong Number?

Definition

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, if their sum equals the original number, then that number is called strong.

Understanding Factorials

The factorial of a non-negative number n is written as n!, resulting from multiplying all positive whole numbers from 1 up to n.

Factorial Formula: n! = n × (n-1) × (n-2) × ⋯ × 2 × 1

Special Case: When n=0, the factorial is 1, so 0! = 1

Factorials are used in mathematics and statistics, mainly in problems involving permutations and combinations.

Factorial Examples

Number Factorial Calculation Result
0! 1 (by definition) 1
1! 1 1
2! 2 × 1 2
3! 3 × 2 × 1 6
4! 4 × 3 × 2 × 1 24
5! 5 × 4 × 3 × 2 × 1 120
8! 8 × 7 × 6 × 5 × 4 × 3 × 2 × 1 40320

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

Strong Number Examples

Example 1: 40585 (Strong Number)

To verify if 40585 is a strong number:

Digits: 4, 0, 5, 8, 5

Factorial Calculations:

Sum of Factorials: 24 + 1 + 120 + 40320 + 120 = 40585

Verification: 40585 = 40585 ✓

Conclusion: 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 factorion, which is a special case of strong numbers.

Example 2: 145 (Strong Number)

To check if 145 is a strong number:

Digits: 1, 4, 5

Factorial Calculations:

Sum of Factorials: 1 + 24 + 120 = 145

Verification: 145 = 145 ✓

Conclusion: Since the sum of the factorials equals the original number, 145 is a strong number.

Example 3: 123 (Not a Strong Number)

To verify if 123 is a strong number:

Digits: 1, 2, 3

Factorial Calculations:

Sum of Factorials: 1 + 2 + 6 = 9

Verification: 9 ≠ 123 ✗

Conclusion: Since 9 is not equal to 123, it is clear that 123 is not a strong number.

Steps for Checking if a Number is Strong

Step-by-Step Process

Step 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.

Step 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.

Step 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.

Step 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.

Step 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.

Step 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.

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.

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

Example Output:

For input 123:

The factorials are:

Sum: 1 + 2 + 6 = 9

Since 9 ≠ 123, the output is:

123 is not a Strong Number.

For input 145:

The factorials are:

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:

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 Output:

For input 40585:

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

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:

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:

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 Output:

For input 145:

The factorials are:

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

Enter a number: 145
145 is a Strong Number.

For input 123:

The factorials are:

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

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:

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 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.

Code:

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:

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].

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.

Related Articles