Strong Number in Python
In this tutorial, we will learn a Python program to find a given number is a Strong number or not.
What is a strong number?
A Strong number is a special number whose sum of the all digit factorial should be equal to the number itself.
To find a whether given number is strong or not. We pick each digit from the given number and find its factorial, and we will do this every digit of the number.
Once we get the factorial of all digit, then we do the sum of factorials. If the sum is equal to the given number then the given number is strong otherwise not.
For example - The given number is 145, we have to pick each digit and find the factorial 1! = 1, 4! = 24, and 5! = 120.
Now, we will do the sum of the factorials, we get 1+24+120 = 145, which is exactly the same as the given number. So we can say that 145 is a strong number.
We got the logic of the strong number. Now implements it using the Python Program.
Sample Input: num = 132
Sample Output: Given number is not a strong number
Explanation: 1! + 3! + 2! = 9 which is not equal to the 132
Sample Input: num = 145
Sample Output: Given number is a strong number.
Python Program to Find Strong Number
Below is the code of the Python program to print the given number is a strong or not.
Enter a number: 145 Given number is a strong number.
In the above code
Suppose user enter the value = 145 and sum = 0
Assigning initial values
Now understand the loop iteration. First Iteration
Now, we entered in the nested while loop. It calculates the factorial of 5 is 120.
Now, it enters into nested While loop. Here, it calculates the factorial of 4 = 24.
The factorial of 1 is 1
Here, the temp = 0 so, the while loop condition fails.
If (num == sum) Now, we check the condition whether the user enter number is exactly equal to sum or not. If this condition returns True, then it is strong Number, else it is not Strong Number.
We have complete the program using the while loop. We can also use for loop to find whether a given number is strong or not.
Strong Number Using the for loop
We can also find the strong number using for loop. The logic is the same as above program, the while loop is replaced by for loop.
Enter the Number:145 Factorial of 5 = 120 Factorial of 4 = 24 Factorial of 1 = 1 Sum of Factorials of a Given Number 145 = 145 The given number is a Strong Number
Python Program to find strong number using factorial function
Enter the Number: 145 Factorial of 5 = 120 Factorial of 4 = 24 Factorial of 1 = 1 Sum of Factorials of a Given Number 145 = 145 The given number is a Strong Number
In the above code,
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week