PHP Armstrong Number
In this article, we'll discuss how to check if a number is an Armstrong number in PHP. An Armstrong number is a number that is equal to the sum of its digits raised to the power of the number of digits.
Syntax
function isArmstrong($number) {
$sum = 0;
$totalDigits = strlen((string)$number);
$num = $number;
while ($num > 0) {
$digit = $num % 10;
$sum = $sum + pow($digit, $totalDigits);
$num = (int)($num / 10);
}
return $number == $sum;
}
Example
echo isArmstrong(153) ? "Yes" : "No"; // Output: "Yes"
echo isArmstrong(371) ? "Yes" : "No"; // Output: "Yes"
echo isArmstrong(9474) ? "Yes" : "No"; // Output: "Yes"
echo isArmstrong(1634) ? "Yes" : "No"; // Output: "Yes"
echo isArmstrong(9475) ? "Yes" : "No"; // Output: "No"
Explanation
The isArmstrong
function accepts a number as an argument and checks if the number is an Armstrong number or not. The function first calculates the total number of digits in the number using strlen
function. Then it keeps dividing the number by 10 and calculates the sum of the power of the digits using pow
function. Finally, if the sum is equal to the original number, the function returns true, indicating that the number is an Armstrong number, else it returns false.
Use
You can use this function to check if a number is an Armstrong number in PHP. Armstrong numbers are used in mathematical problems, and this function can be helpful in solving such problems.
Important Points
- An Armstrong number is a number that is equal to the sum of its digits raised to the power of the number of digits.
- To check if a number is an Armstrong number, we calculate the total number of digits in the number, and then calculate the sum of the power of each digit.
- The
pow
function is used to calculate the power of a digit. - In PHP,
strlen
function is used to calculate the length of a string.
Summary
In this article, we discussed how to check if a number is an Armstrong number in PHP. We saw the syntax of the isArmstrong
function and explained how it calculates the sum of the power of each digit to check if the number is an Armstrong number or not. We also explained the importance of Armstrong numbers and how this function can be helpful in solving mathematical problems.