当前位置:网站首页>C language classic exercise (1) - "daffodil number"“

C language classic exercise (1) - "daffodil number"“

2022-07-23 09:15:00 it_ NunU

C Interesting language exercises —— Narcissistic number



Topic introduction

Narcissus number refers to “ The number itself is equal to the cubic sum of each number ” Three digits of .
for example :123 It's Narcissus , because 123 = 13 + 23 + 33. Please calculate the number of all daffodils .


One 、 Method explanation

1. Method 1

First, determine the number of daffodils n The possible value range of , because n It's a three digit number , So the value is 100~999 Between , It's not hard to see. , This is a technology controlled cycle . about n Every possible value of , First, separate the single digit numbers ( k )、 Ten digits ( j )、 Hundred digits ( i ), And then through n And j3 + k3 + i3 Compare whether it is equal , That's for sure n Is it the number of daffodils .

2. Method 2

Set the hundreds of daffodils 、 Ten digits 、 The single digits are i、j、k, By traversing i、j、k All possible values of , Then judge i * 100 + j * 10 + k And i * i * i + j * j * j + k * k * k Whether it is equal or not , The calculation can be completed .(* notes : Because daffodils are in three digits , Its hundreds of digits i The value of cannot be 0

Two 、 Code implementation

Law 1 The code is as follows ( Example ):

int main()
{
    
	int i, j, k, n;
	for ( n = 100; n < 1000; n++)
	{
    
		i = n / 100;				//  Separate hundreds of digits 
		j = (n - i * 100) / 10;		//  Separate out ten digits 
		k = n % 10;					//  Separate out one digit 
		if (n == i*i*i + j*j*j + k*k*k) //  Determine whether the number of daffodils is satisfied 
		{
    
			printf("%d ", n);
		}
	}
	printf("\n");
	return 0;
}
 Run the renderings 

 Operation diagram

Law two The code is as follows ( Example ):

int main()
{
    
	int i, j, k;
	for ( i = 1; i <= 9; i++)		  //  Traverse all possible values of hundreds of digits 
	{
    
		for ( j = 0; j <= 9; j++)	  //  Traverse all possible values of ten digits 
		{
    
			for (k = 0; k <= 9; k++)  //  Traverse all possible values of each number 
			{
    
				//  Judge 
				if (i*100 + j*10 + k == i*i*i + j*j*j + k*k*k)
				{
    
					printf("%d ", i * 100 + j * 10 + k);
				}
			}
		}
	}
	return 0;
}
 Run the renderings 

 design sketch

summary

The above is a simple number of daffodils C Language implementation method , If there are mistakes in the text, please point them out ~
If it helps you , Attention and praise Well .
Look forward to making progress with you !

原网站

版权声明
本文为[it_ NunU]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/204/202207230058029161.html