检查一个数字是否为合数
合数是一个数如果它等于它的因数的和,那就是原始数等于它所有因数的和不包括这个数本身。在本文中,我们已经讨论了如何检查一个数字是否完美。在本文中,我们将讨论如何在PHP中做同样的事情。
例子
1 2 3 4 5 6 7 8 9 10 11 12 | Input : 6 Output : Perfect Number Explanation: factors of 6 are 1, 2, 3, 6 sum of its factors (excluding the number itself) = 1 + 2 + 3 = 6 Input : 24 Output : Not Perfect Number Explanation : factors of 24 are 1,2,3,4,6,8,12,24 sum of its factors(excluding the number itself) = 1 + 2 + 3 + 4 + 6 + 8 + 12 = 36 |
这样做的目的是,我们将遍历范围[1,N]中的每个数字,并检查它是否是给定数字N的因数。最后是变量$sum等于原数字那么给定的数字就是一个合数。
下面是上述思想在PHP中的实现:
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 28 29 30 | <?php // Function to check if a number is perfect function isPerfectNumber($N) { // To store the sum $sum = 0; // Traversing through each number // In the range [1,N) for ($i = 1; $i < $N; $i++) { if ($N % $i == 0) { $sum = $sum + $i; } } // returns True is sum is equal // to the original number. return $sum == $N; } // Driver's code $N = 6; if (isPerfectNumber($N)) echo " Perfect Number"; else echo "Not Perfect Number"; ?> |
输出
1 | Perfect Number |