Question #37471

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 1
3

+ 5
= 1 + 125
+ 27 = 153 and so 153 is a narcissistic number, while 351 is 3
3
+ 5
3
+ 1
3
= 27 + 125 + 1 = 153
≠ 351. 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.
1

Expert's answer

2013-12-05T10:55:49-0500

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 1+3+5=1+125+27=1531 + 3 + 5 = 1 + 125 + 27 = 153 and so 153 is a narcissistic number, while 351 is 33+53+13=27+125+1=15335133 + 53 + 13 = 27 + 125 + 1 = 153 \neq 351.

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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!
LATEST TUTORIALS
APPROVED BY CLIENTS