
php水仙花数是什么?
所谓“水仙花数”,是指一个 n 位数 ( n≥3 ),它的每个位上的数字的 n 次幂之和等于它本身。
PHP求水仙花数的程序,有多种写法:
方法示例一:
<?php
header("content-type:text/html;charset=utf-8;"); //设置页面编码为 utf-8
//以下代码求解1000以内的水仙花数
echo '<p>1000以内的水仙花数: </p>';
for ( $i = 100; $i < 1000; ++ $i )
{
$hundreds = floor( $i / 100); //分解出百位
$tens = floor( $i / 10 ) % 10; //分解出十位
$ones = floor( $i % 10 ); //分解出个位
if (bcpow($hundreds,'3')+bcpow($tens,'3')+bcpow($ones,'3') == $i)
echo $i."";
}
?>输出:
立即学习“PHP免费学习笔记(深入)”;
1000以内的水仙花数: 153 370 371 407
方法示例二:
<?php
for($q=1;$q<=9;$q++){
for($w=0;$w<=9;$w++){
for($e=0;$e<=9;$e++){
if($q*$q*$q + $w*$w*$w + $e*$e*$e ==
100*$q + 10*$w + $e){
echo "$q$w$e"."<p>";
}
}
}
}输出:
立即学习“PHP免费学习笔记(深入)”;
153 370 371 407
方法示例三:
<?php
function cube( $n )
{
return $n * $n * $n;
}
function is_narcissistic ( $n )
{
$hundreds = floor( $n / 100); //分解出百位
$tens = floor( $n / 10 ) % 10; //分解出十位
$ones = floor( $n % 10 ); //分解出个位
return (bool)(cube($hundreds)+cube($tens)+cube($ones) == $n);
}
for ( $i = 100; $i < 1000; ++ $i )
{
if ( is_narcissistic($i) )
echo $i."\n";
}方法示例四:
<?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免费学习笔记(深入)”;
153 370 371 407 1634 8208 9474 54748 92727 93084
方法示例五:
<html>
<head>
<title></title>
</head>
<body>
<?php
function winter($num)
{
if($num<1000){
//定义个位
$ge=$num%10;
//定义十位
$ten=(($num%100)-$ge) /10;
//定义百位
/*floor取整,忽略小数点后面的所有数*/
$hundred=floor($num/100);
$sum1=$ge*$ge*$ge+$ten*$ten*$ten+$hundred*$hundred*$hundred;
if($sum1==$num){
return 1;
} else{
return 0;
}
} else{
return -1;
}
}
if(winter(371)==-1) {
echo "大于1000的数";
}else{
if(winter(371)) {
echo "Yes";
}
else{
echo "No";
}
}
?>
</body>
</html>输出:
立即学习“PHP免费学习笔记(深入)”;
Yes
相关推荐:《PHP教程》
以上就是php水仙花数是什么的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号