Answer on Question#37471 - Programming, C++
1. Exercise 2: Narcissistic Number
A narcissistic number is a positive integer which is equal to its digits sum raised to the number of digits in the integer. For example the integer 153 has three digits, then and so 153 is a narcissistic number, while 351 is .
The numbers 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 407, 1634, 8208, 24678051 are all narcissistic numbers.
Define the function: bool isNarcissistic(int)
Write a main function on which reads a positive integer, calls the function isNarcissistic(), and prints whether the integer is a narcissistic number or not.
Solution.
#include <iostream>
#include <cmath>
using namespace std;
bool isNarcissistic(int n)
{
int b, buf = 0;
int iSave = n;
int i = 0;
while (n > 0)
{
b = n % 10;
n /= 10;
i++;
}
n = iSave;
while (n > 0)
{
b = n % 10;
n /= 10;
buf += (int)pow(b, i);
}
if (iSave == buf) { return true; }
else { return false; }
}
int main(int argc, char * argv[])
{
int n;
cout << "Enter the number:" << endl;
cin >> n;
if (isNarcissistic(n))
{ cout << "This number is a narcissist!" << endl; }
else
{ cout << "This number is not a narcissistic!" << endl; }
system("pause");
return 0;
}
Comments