In this post, I am writing a small PHP program to find the Magic number. A magic number is a number in which the iterative process of summing its digits eventually leads to a single-digit number, and that single-digit number is 1.
Here’s a simple PHP program to find whether a given number is a magic number or not:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<?php function isMagicNumber($number) { while ($number > 9) { $sum = 0; // Calculate the sum of digits while ($number > 0) { $sum += $number % 10; $number = (int)($number / 10); } $number = $sum; } return $number === 1; } // Example usage $numberToCheck = 19; if (isMagicNumber($numberToCheck)) { echo "$numberToCheck is a magic number.\n"; } else { echo "$numberToCheck is not a magic number.\n"; } ?> |
In this program, the isMagicNumber() function takes a number as an argument and iteratively sums its digits until a single-digit number is obtained. The process continues until the single-digit number is 1 or less. If the final single-digit number is 1, the original number is a magic number.
You can change the value of $numberToCheck to test different numbers. If the number is a magic number, the program will output that it’s a magic number; otherwise, it will indicate that it’s not.
Hope this program helps you to learn the concepts of PHP and also to find the magic number using PHP language.