php实现水仙花数示例分享

Rabia ·
更新时间:2024-09-20
· 570 次阅读

自幂数,又称阿姆斯特朗数,民间通称水仙花数。实则只有3位自幂数才是水仙花数。4位5位6位等等各有别的叫法。

代码如下:
<?php
//阿姆斯特朗数:一个k位数,它的每个位上的数字的k次幂之和等于它本身。(例如:1^3 + 5^3 + 3^3 = 153)
class Armstrong {

 static function index(){
  for ( $i = 100; $i < 100000; $i++ ) {
   echo self::is_armstrong($i) ? $i . '<br>' : '';
  }
 }
 static function is_armstrong($num){
  $s = 0;
  $k = strlen($num);
  $d = str_split($num);
  foreach ($d as $r) {
   $s += bcpow($r, $k);
  }
  return $num == $s;
 }

}
Armstrong::index();

您可能感兴趣的文章:PHP求小于1000的所有水仙花数的代码



示例 水仙花数 PHP

需要 登录 后方可回复, 如果你还没有账号请 注册新账号