水仙花數(100-999).水仙花數是指一個 3 位數,它的每個位上的數字的 3次冪之和等於它本身
c++代碼
int i=100;
while(i<=999){
int sum=0;
int temp=i;
int k=0;
while(temp!=0){
k=temp%10;
sum=sum+k*k*k;
temp=temp/10;
}
if(sum==i){
cout<<sum<<" ";
}
i++;
}
shell 代碼
# @author sugar
# time 2020年 01月 01日 星期三 22:33:59 CST
# 水仙花數
i=100
# 外層循環遍歷每個數字(100 - 999)
while [ $i -le 999 ]
do
declare -i sum=0 #存放3個位數和的臨時值
declare -i temp=$i #當前待判斷的值
declare -i k=0 #臨時存放每個位數的值
while [ temp -ne 0 ]
do
k=$(($temp % 10))
temp=$(($temp/10))
sum=$(($sum+$k*$k*$k))
done
# 如果相等即爲水仙花數
if [ $sum -eq $i ]
then
echo -e "$sum \c"
fi
# i++
i=$(($i + 1))
done