Find all "daffodil numbers" between 0-100000 and output (c language)

"Narcissus number" refers to an n-digit number whose sum to the nth power of each digit is exactly equal to the number itself.

Example: 153=1^3+5^3+3^3 153 is a daffodil number

Analysis: first calculate how many digits the number has, then calculate the sum of the nth powers of each digit of the number, and finally judge whether the sum and the number themselves are equal.

1. How to calculate how many digits the number has?

Example: 1 is composed of 1 digit, 12 is composed of 2 digits, 123 is composed of 3 digits, and 1234 is composed of 4 digits.

Dividing the number by 10 strips off a single digit, and dividing the result by 10 continues to divide by 10 to strip off each digit.

1: 1/10==0 (end)

1 consists of 1 digit

12: 12/10==1 (remove 2, leaving only 1)

        1/10==0(end)

12 consists of 2 digits

123: 123/10==12 (stripping 3, leaving only 2 and 1)

         12/10==1 (2 stripped, only 1 left)

         1/10==0(end)

123 consists of 3 digits

1234: 1234/10==123 (stripping 4, leaving only 3, 2 and 1)

           123/10==12 (strip 3, leaving only 2 and 1)

           12/10==1 (2 stripped, only 1 left)

           1/10==0(end)

 2. How to calculate each digit of the number?

   Example: 1 is composed of 1 digit, 12 is composed of 2 digits, 123 is composed of 3 digits, and 1234 is composed of 4 digits.

The number is successively modulo 10 and divided by 10 to get each bit.

1: 1 %10==1 (units)

       1 /10==0(end)

12: 12%10==2 (units)

        12/10==1

        1 %10==1 (tens)

       1 /10==0(end)

123: 123%10==3 (units)

         123/10==12

         12%10==2 (ten digits)

         12/10==1

        1 %10==1 (hundreds)

         1 /10==0(end)

1234: 1234%10==4 (units)

            1234/10==123

            123%10==3 (ten digits)

            123/10==12

            12%10==2 (hundreds)

            12/10==1

            1 %10==1 (units)

            1 /10==0(end)

#include <math.h>
#include <stdio.h>
int main() {
	//打印"0-100000之间的自幂数(包括水仙花数)"
	int i = 0;
	for (i = 0;i < 100000;i++) {
		//1.计算i一共有多少位-n
		int n = 1;
		int temp = i;
		while (temp/10) {
			n++;
			temp = temp / 10;
		}
		//2.计算i的每一位的n次方之和
		temp = i;
		int sum = 0;
		while (temp) {
			sum+=pow(temp % 10,n);
			temp = temp / 10;
		}
		
		//3.判断是否和自身相等
		if (sum == i) {
			printf("%d ",i);
		}
	
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/Jushuzhan/article/details/125800395