strong number in c++
Strong Number in C++
To determine if a number is a strong number in C++, you need to understand what a strong number is and then implement the logic to check for it.
Definition of a Strong Number: A strong number is a number that is equal to the sum of the factorial of its digits.
Steps to Check for a Strong Number: 1. Take the input number from the user. 2. Initialize variables to store the sum of the factorials of the digits and a temporary variable to store each digit of the number. 3. Extract each digit from the input number using the modulus operator (%) and divide the number by 10 to remove the extracted digit. 4. Calculate the factorial of each digit using a loop and multiply it with the sum of the factorials. 5. Repeat steps 3 and 4 until all the digits have been processed. 6. Compare the sum of the factorials with the input number. If they are equal, the number is a strong number; otherwise, it is not. 7. Display the result to the user.
Here is an example implementation of the above steps in C++:
#include <iostream>
// Function to calculate the factorial of a number
int factorial(int num) {
int fact = 1;
for (int i = 1; i <= num; i++) {
fact *= i;
}
return fact;
}
// Function to check if a number is a strong number
bool isStrongNumber(int num) {
int sum = 0;
int temp = num;
while (temp > 0) {
int digit = temp % 10;
sum += factorial(digit);
temp /= 10;
}
return (sum == num);
}
int main() {
int number;
std::cout << "Enter a number: ";
std::cin >> number;
if (isStrongNumber(number)) {
std::cout << number << " is a strong number." << std::endl;
} else {
std::cout << number << " is not a strong number." << std::endl;
}
return 0;
}
This program defines two functions: factorial
and isStrongNumber
. The factorial
function calculates the factorial of a given number, and the isStrongNumber
function checks if a number is a strong number by calculating the sum of the factorials of its digits.
In the main
function, the user is prompted to enter a number. The program then calls the isStrongNumber
function to check if the entered number is a strong number. The result is displayed to the user.
I hope this helps! Let me know if you have any further questions.