
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if a Number is an Armstrong Number in PHP
Armstrong Number
Armstrong number is a number in which the sum of its digits raised to the power of the number of digits is equal to the number itself. In this article, we are going to discuss how we can check if a given number is Armstrong number or not.
Examples
Let's understand Armstrong's Number with the help of some input-output examples.
Input
9474
Output
Yes
Explanation
This is a four digit-number. The digit in this number are 9, 4, 7 and 4.
9474 = 94 + 44 + 74 + 44
= 6561 + 256 + 2401 + 256
= 9474
So, this is an Armstrong number.
Input
153
Output
Yes
Explanation
This is a 3-digit number. The digits in this number are 1, 5, and 3.
153 = 13 + 53 + 33So, this is an Armstrong number.
= 1 + 125 + 27
=153
Solution Approach
We will take an integer as input. We first write a function to count the total number of digit in the number. Now we initialize a variable to store the sum and store original number in any variable. Now, we extract each digit of the number using modulo operator and add the digit raised to the power of total number of digit. Finally we check if the sum calculated is equal to original number.
Implementation in PHP
Follow the below steps to implement the solution of the above problem in PHP -
- We write a function to count the number of digits in a number.
- Now, write another function to check if a number is an Armstrong number or not.
- Initialize a variable sum and store the original number
- Now extract each digit of the number using the modulo operator one by one and add the digit raised to the power of count of digit.
- Drop the last digit using the division operator.
- After coming out of the loop, check if the sum is equal to the original number.
- If yes then this is an Armstrong number.
Example
Following is the implementation in PHP following the above discussed implementation steps.
<?php // Function to count the number of digits in a number function countDigits($num) { return strlen((string)$num); } // Function to check if a number is an Armstrong number function isArmstrong($num) { $k = countDigits($num); $sum = 0; $originalNum = $num; while ($num > 0) { $ld = $num % 10; $sum += pow($ld, $k); $num = (int)($num / 10); } return $sum == $originalNum; } $number = 153; if (isArmstrong($number)) { echo "$number is an Armstrong number."; } else { echo "$number is not an Armstrong number."; } ?>
Output
153 is an Armstrong number.
Time Complexity: O(d * n), where d is the number of digits and n is the raised power on each digit
Space Complexity: O(1), constant space