Narcissistic decimal number | Rosetta Code | #5

URL to the problem page: https://rosettacode.org/wiki/Narcissistic_decimal_number


A Narcissistic decimal number is a non-negative integer, n, that is equal to the sum of the m-th powers of each of the digits in the decimal representation of n, where m is the number of digits in the decimal representation of n.

Narcissistic (decimal) numbers are sometimes called Armstrong numbers, named after Michael F. Armstrong.
They are also known as Plus Perfect numbers.

An example

  • if n is 153 
  • then m, (the number of decimal digits) is 3 
  • we have 13 + 53 + 33 = 1 + 125 + 27 = 153 
  • and so 153 is a narcissistic decimal number 


Generate and show here the first 25 narcissistic decimal numbers.



#include <iostream>
using namespace std;

int power(int aint b) {
    int result = 1;
    for (int i = 0; i < b; i++) {
        result *= a;
    }
    return result;
}

int main()
{
    int tmp, tmp2, digits, i, j, k, sum, counter = 0;

    cout << "First 25 narcissistic decimal numbers are:" << endl;
    for (i = 0; counter < 25; i++) {
        digits = 1;
        sum = 0;
        tmp = i;
        tmp2 = tmp;
        while (tmp >= 10) {
            tmp /= 10;
            digits++;
        }
        tmp = tmp2;
        for (j = digits; j > 0; j--) {
            k = tmp / (power(10, (j - 1)));
            sum += (power(k, digits));
            tmp -= (power(10, (j - 1)) * k);
        }
        if (sum == tmp2) {
            counter++;
            cout << tmp2 << endl;
        }
    }
    return 0;
}



Comments

My photo
Ercan Tomac
instagram.com/ercantomac