Check Narcissistic Number
Check Narcissistic Number in C++ (4 Programs)
IntermediateTopic: Advanced Number Programs
C++ Check Narcissistic Number Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#include <iostream>
#include <cmath>
using namespace std;
bool isNarcissistic(int num) {
int original = num;
int n = 0, sum = 0;
// Count digits
int temp = num;
while (temp != 0) {
temp /= 10;
n++;
}
// Calculate sum of digits raised to power n
temp = num;
while (temp != 0) {
int digit = temp % 10;
sum += pow(digit, n);
temp /= 10;
}
return sum == original;
}
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
if (isNarcissistic(num)) {
cout << num << " is a Narcissistic number" << endl;
} else {
cout << num << " is not a Narcissistic number" << endl;
}
return 0;
}Output
Enter a number: 153 153 is a Narcissistic number
Understanding Check Narcissistic Number
A Narcissistic number (also called Armstrong number) is a number that equals the sum of its digits each raised to the power of the number of digits. For example, 153 = 1³ + 5³ + 3³. This program demonstrates 4 different methods.
Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.