linux training assignments, shell programming calculation problems

Keywords: shell

Training assignment

Write a shell program to display the menu. Use the function to realize the simple menu function. The value of n is input by keyboard

**(1) Calculate the sum of odd numbers from 1 to n**
**(2) Calculate the factorials from 1 to n**
**(3) Calculate all primes from 1 to n**
**(4) Exit the program. * *

Please enter function select and number: 1 1000
Requirements: self designed program. As for the function of prime number calculation, we should choose the efficient algorithm as far as possible.
Note: you can choose one of the following methods to implement function (3): calculate all primes from 1 to n.

#!/bin/bash
#Enter the cycle of calculation
#Calculate the sum of odd numbers from 1 to n
function one(){
    echo "-----Start calculating 1 to n Please enter the number you want to calculate-----"
    read num
    sum=0
    for((i=1;i<=$num;i++))
    do  
        if [ $((i%2)) -ne 0 ];then
        let "sum=$sum+$i"
        fi
    done
    echo "The calculation results are as follows $sum"
}
function two(){
    echo "-----Start calculating 1 to n Please enter the number you want to calculate-----"
    read num
    sum=1
    for((i=1;i<=$num;i++))
    do  
        let "sum=$sum*$i"
    done
    echo "The calculation results are as follows $sum"
}
function three(){
    echo "-----Start calculating 1 to n Please enter the number you want to calculate-----"
    read num
    declare -l a 
    for((i=1;i<=$num;i++))
    do 
        for((j=1;j<=i;j++))
        do 
            b=$(( $i%$j ))
            if [[ $b -eq 0 ]]; then
                a=$a+1
            fi
        done
        if [[ $a -eq 2 ]]; then
            echo -n $i " "
        fi
        a=0
    done
    echo
}
#Convenient program wireless loop
while ((flag=1))
do
    echo "-----Please choose what you want to do------"
    echo "**    (1)Calculate 1 to n The sum of odd numbers of;       **"
    echo "**    (2)Calculate 1 to n The factorial of;           **"
    echo "**    (3)Calculate 1 to n All prime numbers of;       **"
    echo "**    (4)Exit the program.                 **"
    read selected
    case $selected in
    1)
        one;;
    2)
        two;;
    3)
        three;;
    4) 
        echo "Exiting program..."
        exit;;
    esac
done
    

Posted by CraigRoberts on Mon, 29 Jun 2020 21:39:36 -0700