×

Python Strong Number

Strong Number- Logic

  • Divide each of the number's digits into separate units to determine if it is a strong number or not.
  • The factorial of each digit must then be determined. The values produced for each digit following the factorial operation will then be added.
  • In the end, the sum needs to be compared to the supplied number. The number is a strong one if the response is yes.

Algorithm

To determine whether a given number is a strong number or not, apply the algorithm provided below.

  • Obtain the required number and use it as input to determine if it is a strong number or not. Let's assign this input number to the variable N.
  • Put N's value in a short-term variable called temp_N.
  • Put a variable's value, such as "sum," to zero. This will record the factorial sum for every digit of N.
  • The last digit of the number needs to be preserved in a variable, such as the last digit = N % 10.
  • It is necessary to keep the factorial of the last digit in a variable called fact.
  • Every time the factorial of the last digit is found, the sum should be raised.
    sum = sum + fact
  • The number must be divided by 10 to become smaller in units after each factorial operation.
    N=N/10
  • Until N > 0, then repeat steps 4 through 7.
  • When the loop is finished, the condition sum = temp N should be tested to see if the sum equals the number. If the answer is affirmative, the input number is a strong one.

Strong Number Program Implementation in Python

The algorithm described above is used to build the following Python computer code, which enables us to detect whether a given integer is a strong number or not.

Strong Number with while Loop in Python

Example 1:

sum = 0
N = int(input("Enter a number: "))
temp_N = N
while(N):
    k = 1
    fact = 1
    r = N % 10
while(k <= r):
        fact = fact * k
        k = k + 1
    sum = sum + fact
    N = N//10
if(sum == temp_N):
    print(str(temp_N) + " is a strong number")
else:
    print(str(temp_N) + " is not a strong number")

Output:

Strong Number in Python
  • The user is initially prompted for input when the program is run. We can pass the necessary number to determine if it is a strong number or not. In this instance, we entered after passing 145.
  • The response is "145 is a strong number," which is the appropriate output. This is demonstrated in the screenshot above.
  • Passing another input now. Once more, we exceeded 163. Since 163 is a weak number, we obtained the results depicted below.
Strong Number in Python

The software code that we just looked at conducts a simple number check. We might occasionally need to confirm this for several numbers at once.

Finding Strong Numbers in a List Using a Python Program

We'll employ another Python method for this. We can do this with the aid of the Python program code listed below. Examine the Python programming code that follows carefully to observe how each component carries out its intended function.

Example 2:

# Compute factorial
def factorial1(N): 
if(N == 0 or N == 1): 
        fact = 1
    else: 
        fact = N * factorial1(N - 1) 
    return fact 
# Check for strong number 
def strong_number(list): 
    n_list =[]   
    for i in list: 
        temp_N = i 
        sum = 0
        while(temp_N): 
            r = temp_N % 10
            sum += factorial1(r) 
            temp_N = temp_N // 10
if(sum == i): 
            n_list.append(i) 
        else: 
            pass                
    return n_list           
# Input
a = [10, 25, 2, 121, 145, 786, 49, 1, 20900] 
strong_num_list = strong_number(a) 
print(strong_num_list)

Output:

Strong Number in Python
  • The Python program code presented above is divided into three sections. Firstly the fact N() function, which determines the factorial of the parameterized number. Second, there is the strong number() function, which adds up each digit's factorial sum in the given number.
  • The strong_number() function accepts a list as a parameter since we want to list several numbers as input. The strong_number function first creates a bare list called n list.
  • A while loop computes the factorial total for each digit. The method then returns the value if the sum does equal the supplied number.
  • The input portion is the third component of the program. Simply giving the necessary values and running the application will allow us to pass them.
  • The list is given to the strong number function, which returns one or more strong number(s) stored in the list variable strong_num_list.
  • Finally, we output the list of all potential string values.

From the input list of values, as shown above, we obtained an output list that contained the values 2, 145 and 1. The result is precise. Let's run the program once more with a new set of parameters.

Example 3:

#  Factorial Computation
def factorial1(Number): 
if(Number == 0 or Number == 1): 
        fact = 1
    else: 
        fact = Number * factorial1(N - 1) 
    return fact 
# Check for strong number 
def strong_number(list): 
    n_list =[]   
    for i in list: 
        temp_N = i 
        sum = 0
        while(temp_N): 
            r = temp_N % 10
            sum += factorial1(r) 
            temp_N = temp_N // 10
if(sum == i): 
            n_list.append(i) 
        else: 
pass                
    return n_list           
# Input
a = [67, 87, 13, 949, 71, 890, 1018, 73, 1, 0] 
strong_num_list = strong_number(a) 
print(strong_num_list)

Output:

Strong Number in Python

As seen above, a list with the values 1 and 0 as output has been returned. Consequently, the values on the list are strong numbers.

  • Now, lets pass a different list of values to the above written code.
input_vals = [67, 87, 13, 949, 71, 890, 1018, 73, 11, 90]

Output Obtained

Strong Number in Python

The output has been returned as a blank list, as seen above. As a result, none of the values in the list are considered to be strong numbers.

Strong Number with for Loop in Python

Example:

sum = 0
number=int(input("enter a number:"))
temp = number
while(temp > 0):
   fact = 1
   rem = temp % 10
   for i in range(1, rem + 1):
      fact = fact * i
print("Factorial of %d = %d " %(rem, fact))
   sum = sum +fact
   temp = temp // 10


print("Sum of factorials of the number %d = %d " %(number,sum))
if(sum == number):
print("Strong Number")
else:
print("Not a strong number")

Output:

Strong Number in Python

Strong Number Python Program Employing Function

To find the strong number, we employ a built-in Python function.

Example:

import math
number = int(input("Enter Number: "))
sum = 0
temp = number
while(temp>0):
   remainder = temp % 10
   fact = math.factorial(remainder)
print("Factorial of %d = %d" %(remainder, fact))
   sum = sum + fact
   temp = temp // 10


print("Sum of factorials of a number %d = %d" %(number,sum))
if(sum == number):
print("Strong number")
else:
print("not a strong number")

Output

Strong Number in Python

We have imported math since we are using a built-in function named factorial() found in the math library. The factorial of a single digit was calculated using this factorial() alone. As a result, it saves us from having to repeatedly calculate the factorial of each digit.

Conclusion

An idea in mathematics known as a strong number has several uses. Strong numbers are particular numbers where the sum of all digit factorials equals the sum itself. Python's numerous features enable us to swiftly and efficiently construct reliable number-checking applications.


Related Topics

Python Dictionary clear() method

Python Dictionary clear() method The dictionary.clear() method in Python removes all the elements from a dictionary. Syntax dictionary.clear() Parameter NA Return None Example 1 # Python program explaining # the dictionary.clear() method # initialising the dictionary fruits =...

1 minute read.

Allocate a minimum number of pages in python

You have given a sorted array of size n which represents the number of pages in n different books and an integer value which denotes the number of students. We...

4 minutes read.

Python String replace() method

Python String replace() method The string.replace() method in Python returns a copy of the string with all occurrences of substring old replaced by new. Syntax replace(old, new[, count]) Parameter old: This parameter represents a substring you want to...

2 minutes read.

Best Database for Python

Database The collection of structured data or information in an organized format in a computer system is known as Database. The data is inserted, deleted, updated, controlled, or manipulated in a...

6 minutes read.

Python String strip() method

Python String strip() method The string. strip() method in Python removes any leading (spaces at the beginning) and trailing (spaces at the end) characters (space is the default leading character to...

1 minute read.

Assertion Errors and Attribute Errors in Python

Assertion Error in Python In Python, the assert condition is used to continue the execution if the given statement displays true. If the assert statement displays false, it raises Assertion Error...

3 minutes read.

Python logging Module

Python logging Module Introduction By logging word we understand the tracking of the events which happens when we run some software. Logging process is very important part for developing software, debugging...

12 minutes read.

How to find square root in python

How to find Square Root of a number In Python Python makes a lot of tasks easier by using different functions, modules, and libraires. There is an inbuilt function in Python...

6 minutes read.

Idle python download for Windows

Here, we will be discussing how to get the answer to all questions related to installing Python on Windows. What is IDLE? Integrated Development and Learning Environment, or IDLE, is a shorthand....

3 minutes read.

NSE Tools In Python

About NSE NSE (National Stock Exchange) of India Limited is the advanced stock exchange of India. It is located in Mumbai, Maharastra and It was organized in 1992. It was...

2 minutes read.

Method Overloading in Python

Overloading is a capability of a method and operator to behave differently according to the nature of parameters. Overloading is popular because it provides a good number of advantages: Reusability of code.Reduces...

3 minutes read.

How to Install Python

Python Installation Guide Step by Step Installing Python is quite simple and easy. In this tutorial, we will show stepwise procedure to install Python and set up the Python environment in different...

2 minutes read.

Python e-book free download

Python is a booming language these days. It has many applications for making code easier; it is also an open-source language. There are many sources to learn python. In this...

3 minutes read.

What Does the Percent Sign (%) Mean in Python?

In python, the percent sign is called modulo operator " %, " which returns the rest of partitioning the left-hand operand by the right-hand operand. Example: value1 = 8 value2 = 2 remainder =...

4 minutes read.

Python NewLine

In python, a new line character denoted by "\n" is known as an escape character or escape sequence, and it will force the cursor to change its position to the next...

6 minutes read.

Convert uppercase to lowercase in Python

Python String lower() By using the built-in string lower() method, all the uppercase characters can be converted into lowercase characters in a string, The lowercased string from the given string is returned...

1 minute read.

How to check data type in python

The data type represents the nature of a variable; it determines what kind of data it can store and what operations can be carried out on it. There are five...

4 minutes read.

tell() function in Python

Introduction The tell() function in Python is used to return the current position of the file read/write pointer within the file. An integer value is returned by this method, and it...

2 minutes read.

Python Set remove() method

Python Set remove() method The set.remove() method in Python removes the specified element from the set if it is present in the set else this method will raise an error if the specified item does...

2 minutes read.

Python Statistical Module

Python Statistical Module The Python statistical module provides various functions that we can use in our Python program, to perform mathematical statistics operations on the numerical data given to us. The...

8 minutes read.