Dear viewers, are your big heads filled with questions? Haha, don’t be confused, today I’m going to introduce you to another fun method. The vernacular translation of the title of this article is “Use PHP to check whether a number is an Armstrong number.” The Armstrong number is actually the narcissus number, so what exactly is this number? Is it a daffodil? How to implement it using PHP program? Let's introduce them one by one~
First of all, I will introduce to you the definition of narcissus number, that is, Armstrong number:
The narcissus number is also called a supercomplete number. Variable, narcissistic number, autoexponential number, Armstrong number or Armstrong number. The narcissus number is a 3-digit number in which the sum of the 3rd powers of the digits in each digit is equal to itself (for example: 1^3 5^3 3^3 = 153).
You should understand now, then let’s continue:
Open the editor directly and enter the code!
<?php function armstrong_number($num) { $sl = strlen($num); $sum = 0; $num = (string)$num; for ($i = 0; $i < $sl; $i++) { $sum = $sum + pow((string)$num{$i},$sl); } if ((string)$sum == (string)$num) { return "True"; } else { return "False"; } } echo "153是阿姆斯特朗数吗?".armstrong_number(153); echo "<br>21是阿姆斯特朗数吗?".armstrong_number(21); echo "<br>4587是阿姆斯特朗数吗?".armstrong_number(4587);
Let’s run the results and see:
In the above example, we gave three numbers for judgment, which are 153 ,21,4587.
Obviously 153 is Armstrong's number, but neither 21 nor 4587 is, so false is returned.
In fact, if you want to determine whether it is an Armstrong number in a PHP program, the most critical point is its determination formula!
As the above definition says, the number that matches the sum of the three powers of the numbers in each digit is equal to itself is called the Armstrong number, which is also the daffodil number.
Then a key code part in the example is "$sum =$sum pow((string)$num{$i},$sl);
".
Here pow() is a built-in function in PHP, used to calculate x raised to the yth power.
Now, is it easy to understand?
Although it is not difficult, I personally think it is more interesting. I hope this idea can help friends in need~
PHP video tutorialPlease click ->https://www.php.cn/course/list/29/type/2.html
The above is the detailed content of Don't miss the love-hate relationship between PHP and Armstrong numbers. For more information, please follow other related articles on the PHP Chinese website!