当前位置:Gxlcms > PHP教程 > php实现水仙花数代码分享

php实现水仙花数代码分享

时间:2021-07-01 10:21:17 帮助过:19人阅读

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

例子,php实现水仙花数的代码。

  1. //阿姆斯特朗数:一个k位数,它的每个位上的数字的k次幂之和等于它本身。(例如:1^3 + 5^3 + 3^3 = 153)
  2. class Armstrong {
  3. static function index(){
  4. for ( $i = 100; $i < 100000; $i++ ) {
  5. echo self::is_armstrong($i) ? $i . '
    ' : '';
  6. }
  7. } // edit by bbs.it-home.org
  8. static function is_armstrong($num){
  9. $s = 0;
  10. $k = strlen($num);
  11. $d = str_split($num);
  12. foreach ($d as $r) {
  13. $s += bcpow($r, $k);
  14. }
  15. return $num == $s;
  16. }
  17. }
  18. Armstrong::index();

人气教程排行