Krishnamurthy Number in C++ (Strong number or Factorial number)

Profile Picture

vishesh_namdev22056

Thursday, 2024-08-08



A Krishnamurthy number (also known as a Strong number or Factorial number) is a number whose sum of the factorial of its digits is equal to the number itself. For example, 145 is a Krishnamurthy number because 1!+4!+5!=1451! + 4! + 5! = 1451!+4!+5!=145.

Krishnamurthy Number | Learn How to ...

#include <iostream>
#include <cmath>


// Function to calculate factorial of a number
int factorial(int n) {
    if (n == 0 || n == 1) return 1;
    int fact = 1;
    for (int i = 2; i <= n; ++i) {
        fact *= i;
    }
    return fact;
}


// Function to check if a number is a Krishnamurthy number
bool isKrishnamurthy(int num) {
    int originalNum = num;
    int sumOfFactorials = 0;


    while (num > 0) {
        int digit = num % 10;
        sumOfFactorials += factorial(digit);
        num /= 10;
    }


    return sumOfFactorials == originalNum;
}


int main() {
    int num;


    std::cout << "Enter a number to check if it is a Krishnamurthy number: ";
    std::cin >> num;


    if (isKrishnamurthy(num)) {
        std::cout << num << " is a Krishnamurthy number." << std::endl;
    } else {
        std::cout << num << " is not a Krishnamurthy number." << std::endl;
    }


    return 0;
}

How did you feel about this post?

😍 🙂 😐 😕 😡