C Practice Example 13 - Narcissistic Number

100 Classic C Examples

Title:Print all "narcissistic numbers". A "narcissistic number" refers to a three-digit number whose sum of the cubes of its digits equals the number itself. For example, 153 is a "narcissistic number" because 153 = 1^3 + 5^3 + 3^3.

Program analysis:Use a for loop to control numbers from 100 to 999, and decompose each number into its units digit, tens digit, and hundreds digit.

Example

// Created by www.example.com on 15/11/9. // Copyright © 2015 Example. All rights reserved. // #include <stdio.h> int main() { int i, x, y, z; // Traverse the numbers from 100 to 999 for (i = 100; i < 1000; i++) { // Calculate the digits x = i % 10; // ones digit y = (i / 10) % 10; // tens digit z = (i / 100) % 10; // hundreds digit // Calculate the sum of cubes int sum = x * x * x + y * y * y + z * z * z; // Determine whether it is a narcissistic number if (i == sum) { printf("%d\n", i); } } return 0; }

The output result of the above example is:

153
370
371
407 

The following demonstrates how to find and output narcissistic numbers within a specified range in C language:

Example

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

// Function declaration
int countDigits(int num);
int isArmstrong(int num);

int main() {
    int start, end;
   
    // Enter the range
    printf("Enter the start of the range: ");
    scanf("%d", &start);
    printf("Enter the end of the range: ");
    scanf("%d", &end);

    // Output the narcissistic numbers in the range
    printf("Armstrong numbers between %d and %d are:\n", start, end);
    for (int i = start; i <= end; i++) {
        if (isArmstrong(i)) {
            printf("%d\n", i);
        }
    }

    return 0;
}

// Calculate the number of digits
int countDigits(int num) {
    int count = 0;
    while (num != 0) {
        num /= 10;
        count++;
    }
    return count;
}

// Determine whether a number is a narcissistic number
int isArmstrong(int num) {
    int originalNum = num;
    int digits = countDigits(num);
    int sum = 0;

    while (num != 0) {
        int digit = num % 10;
        sum += pow(digit, digits);
        num /= 10;
    }

    return sum == originalNum;
}

100 Classic C Examples

other extensions