水仙花數(Narcissistic Number),又稱阿姆斯壯數,定義為:一個 k 位數,其各位數字的 k 次方之和等於該數本身。最經典的是三位數:153 = 1³ + 5³ + 3³。本文提供通用演算法實現,支援任意位數檢測。
k = strlen($num)str_split($num)k 次方 bcpow($digit, $k)(支援大數)<?php
/**
* 水仙花數(阿姆斯壯數)檢測與掃描
* 使用 bcmath 擴展支援大整數運算
*/
class ArmstrongNumber
{
/**
* 判斷單一數字是否為水仙花數
* @param int|string $num 待檢測數字
* @return bool
*/
public static function isArmstrong($num): bool
{
$numStr = (string)$num;
$k = strlen($numStr);
$sum = '0';
foreach (str_split($numStr) as $digit) {
// bcpow 返回字串,bcadd 字串加法,避免整數溢位
$sum = bcadd($sum, bcpow($digit, $k));
}
return bccomp($sum, $numStr) === 0;
}
/**
* 掃描範圍內所有水仙花數
* @param int $min 起始值(含)
* @param int $max 結束值(含)
* @return array 符合條件的數字陣列
*/
public static function findInRange(int $min, int $max): array
{
$result = [];
for ($i = $min; $i <= $max; $i++) {
if (self::isArmstrong($i)) {
$result[] = $i;
}
}
return $result;
}
}
// 使用範例
$armstrongs = ArmstrongNumber::findInRange(100, 99999);
echo "發現的水仙花數:\n";
foreach ($armstrongs as $n) {
echo "$n\n";
}
/*
輸出結果:
153 (1³+5³+3³)
370 (3³+7³+0³)
371 (3³+7³+1³)
407 (4³+0³+7³)
1634 (1⁴+6⁴+3⁴+4⁴)
8208 (8⁴+2⁴+0⁴+8⁴)
9474 (9⁴+4⁴+7⁴+4⁴)
54748 (5⁵+4⁵+7⁵+4⁵+8⁵)
92727 (9⁵+2⁵+7⁵+2⁵+7⁵)
93084 (9⁵+3⁵+0⁵+8⁵+4⁵)
548834 (6位數)
...
*/
| 位數 | 稱呼 | 已知個數 | 範例 |
|---|---|---|---|
| 1 | 自冪數 | 10 (0-9) | 0, 1, 2, ..., 9 |
| 3 | 水仙花數 | 4 | 153, 370, 371, 407 |
| 4 | 四葉玫瑰數 | 3 | 1634, 8208, 9474 |
| 5 | 五角星數 | 3 | 54748, 92727, 93084 |
| 6 | 六合數 | 1 | 548834 |
| 7 | 北斗七星數 | 4 | 1741725, 4210818, 9800817, 9926315 |
| 39 | 最大已知 | 1 | 115132219018763992565095597973971522401 |
bcpow 呼叫。水仙花數是經典程式練習題,透過 bcmath 擴展可優雅處理任意大小整數,展現 PHP 在數學計算領域的靈活性。