How to solve the C++ narcissistic number problem?

A narcissistic number is an n-digit number that equals the sum of each digit raised to the nth power. For example, 153 is a narcissistic number because 1^3 + 5^3 + 3^3 = 153.

To solve the Armstrong number problem in C++, one can write a program to loop through all possible n-digit numbers, then calculate the sum of the nth powers of its digits, and finally determine if it equals the original number.

Here is a simple C++ program example to solve the Armstrong number problem:

#include <iostream>
#include <cmath>

int main() {
    int num, sum, temp, digit;

    std::cout << "水仙花数有:\n";
    for (int i = 100; i < 1000; i++) {
        num = i;
        sum = 0;

        while (num > 0) {
            digit = num % 10;
            sum += pow(digit, 3);
            num /= 10;
        }

        if (sum == i) {
            std::cout << i << " ";
        }
    }

    return 0;
}

This program will output all 3-digit narcissistic numbers. You can also adjust the range of the loop to search for narcissistic numbers of other digits as needed.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds