shell求水仙花数

水仙花数(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

猜你喜欢

转载自www.cnblogs.com/roseAT/p/12130810.html