How to calculate narcissistic numbers in the C language?

The method of calculating narcissistic numbers in the C language involves using loops and conditional statements. A narcissistic number refers to an n-digit number (where n is greater than or equal to 3) whose each digit raised to the power of n, summed together, equals the number itself.

The specific method of request is as follows:

  1. Using a loop, start from 100 and evaluate each number individually to determine if it is an Armstrong number.
  2. For each number, start by determining the number of digits it has, denoted as n.
  3. Split the number into its individual digits and calculate the nth power of each digit.
  4. Adding together the nth power of each individual number to get a sum.
  5. Check if the sum is equal to the original number, if it is, then it is a narcissistic number and can be printed or saved.

Here is the sample code:

#include <stdio.h>
#include <math.h>

int main() {
    int n, num, digit, sum;
    
    printf("水仙花数有:");
    
    for (num = 100; num < 1000; num++) {
        n = 0;
        sum = 0;
        int temp = num;
        
        // 获取位数n
        while (temp != 0) {
            temp /= 10;
            n++;
        }
        
        temp = num;
        
        // 分解并计算每个位上的数字的n次幂
        while (temp != 0) {
            digit = temp % 10;
            sum += pow(digit, n);
            temp /= 10;
        }
        
        // 判断是否是水仙花数
        if (sum == num) {
            printf("%d ", num);
        }
    }
    
    return 0;
}

The running result is:

There are narcissus numbers: 153 370 371 407.

Numbers between 100 and 999 that are considered narcissistic numbers include 153, 370, 371, and 407.

bannerAds