What is the Narcissus Number?
Daffodil number refers to an n-digit number (n≥3), the sum of the nth power of the digits in each digit is equal to itself.
(For example: 1^3 + 3^3+ 5^3 = 153), this article collects 4 examples of php implementing narcissus number.
Example 1, php implements the number of daffodils:
-
- for($q=1;$q<=9;$q++){
- for($w=0;$w<=9;$w++){
- for($ e=0;$e<=9;$e++){
- if($q*$q*$q + $w*$w*$w + $e*$e*$e ==
- 100*$q + 10*$w + $e){
- echo "$q $w $e "."
";
- }
- }
- }
- }
- ?>
-
Copy code
Example 2. PHP implements the number of daffodils:
-
-
function cube( $n ) - {
- return $n * $n * $n;
- }
function is_narcissistic ( $n )
- {
- $hundreds = floor( $n / 100); //Decompose the hundreds place
- $tens = floor( $n / 10 ) % 10; //Decompose the tens place
- $ones = floor( $ n % 10 ); //Decompose the units digit
- return (bool)(cube($hundreds)+cube($tens)+cube($ones) == $n);
- }
- for ( $i = 100; $i < 1000; ++ $i )
- {
- if ( is_narcissistic($i) )
- echo $i."n";
- }
- ?>
-
-
Copy code
Example 3, php implements the number of daffodils:
-
- //Armstrong number: a k-digit number, the sum of the k-th power of the numbers in each digit is equal to itself. (Example: 1^3 + 5^3 + 3^3 = 153)
- class Armstrong {
- static function index(){
- for ( $i = 100; $i < 100000; $i++ ) {
- echo self: :is_armstrong($i) ? $i . '
' : '';
- }
- }
- static function is_armstrong($num){
- $s = 0;
- $k = strlen($num);
- $d = str_split($num);
- foreach ($d as $r) {
- $s += bcpow($r, $k);
- }
- return $num == $s;
- }
- }
- Armstrong ::index();
-
Copy code
Example 4, PHP implements daffodil number:
-
- ;?php
- function winter($num)
- {
- if($num<1000){
- //Define the ones digit
- $ge=$num%10;
- //Define the tens digit
- $ten=(($num %100)-$ge) /10;
- //Define hundreds place
- /*floor rounding, ignore all numbers after the decimal point*/
- $hundred=floor($num/100);
- $sum1=$ge* $ge*$ge+$ten*$ten*$ten+$hundred*$hundred*$hundred;
- if($sum1==$num){
- return 1;
- } else{
- return 0;
- }
- } else {
- return -1;
- }
- }
- if(winter(371)==-1) {
- echo "A number greater than 1000";
- }else{
- if(winter(371)) {
- echo "Yes" ;
- }
- else{
- echo "No";
- }
- }
- ?>
|