
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If a Number Is a Krishnamurthy Number in C++
Here we will see how to check a number is Krishnamurty number or not. A number is Krishnamurty number, if the sum of the factorial of each digit is the same as the number. For example, if a number is 145, then sum = 1! + 4! + 5! = 1 + 24 + 120 = 145. So this is a Krishnamurty number,
The logic is simple, we have to find the factorial of each number, and find the sum, then if that is the same as a given number, the number is Krishnamurty number. Let us see the code to get a better idea.
Example
#include <iostream> #include <cmath>> using namespace std; long factorial(int n){ if(n <= 1){ return 1; } return n * factorial(n - 1); } bool isKrishnamurty(int number) { int temp = number; int sum = 0; while(number > 0){ sum += factorial(number % 10); number /= 10; } if(sum == temp){ return true; } return false; } int main() { int n = 145; if(isKrishnamurty(n)){ cout << n << " is Krishnamurty Number"; } else { cout << n << " is not Krishnamurty Number"; } }
Output
145 is Krishnamurty Number
Advertisements