In C language, when it comes to algorithms, one of the questions is to find the three-digit "narcissus number". So what is the "narcissus number"?
The daffodil number is a number with n (>=3) digits, which is equal to the sum of the n powers of each number. For example, 153 is a daffodil number, 153=1*1*1+5*5* 5+3*3*3;
Example 1, find the three-digit fairy number in C language.
-
- #include
- main()
- /*
- * To find three-digit numbers, just use 3 for loops;
- * 153 is a narcissus number, 153=1 *1*1+5*5*5+3*3*3;
- */
- {
- int a,b,c;
- for(a=0;a<=9;a++)
- {
- for(b =0;b<=9;b++)
- {
- for(c=0;c<=9;c++)
- {
- //The following judgment is the main algorithm for implementation
- if(a*a*a + b* b*b + c*c*c == 100*a + 10*b + c)
- { /// bbs.it-home.org
- printf("The result is: %d", 100*a + 10* b + c);
- }
- }
- }
- }
- }
Copy code
Example 2, an example of finding the number of daffodils in PHP.
-
-
- $a = array();
- for ($i=0;$i<=9;$i++)
- {
- for ($j=0;$j<=9 ;$j++)
- {
- for ($m=0;$m<=9;$m++)
- {
- if ($i*$i*$i + $j*$j*$j + $m*$ m*$m == 100*$i + 10*$j +$m)
- {
- $a[] = 100*$i + 10*$j +$m;
- }
- }
- }
- }
- print_r ($a);
Copy code
|