mercredi 31 mai 2017

Print number if it matches the sum and product with Shell Script

I am having syntax error with my script, I'm sure i have the logic set but seem to be having issues with the formatting of the script.

The expected workflow is

if n = ((sum) + (product)) then print n and n++ repeat. else n++ repeat.

function sum() {
    local n=$1
    local res=0
    while [ $n -gt 0 ]
    do
        local sdigit=$(( $n % 10 ))
        local n=$(( $n / 10 ))
        local res=$(( $res + $sdigit ))
    done
    echo $res
}

function prod() {
    len=$(echo $1 | wc -c)
    len=$(( $len - 1 ))

    res=1

    for (( i=1; i <= $len; i++ )) 
    do 
         res=$(($res * $(echo $1 | cut -c $i) )) 
    done 
    echo $res
}

#####################################################

n=0
my_prod=$(prod $n)
my_sum=$(sum $n)

while [ $n -le 10 ];
do
    if [ $n = (($my_prod + $my_sum)) ]
    then
        echo "$n"
        n++
    brake
    else
        n++
    fi
done

Aucun commentaire:

Enregistrer un commentaire