Write a bash script that accepts one command line argument which is an integer b
ID: 3677524 • Letter: W
Question
Write a bash script that accepts one command line argument which is an integer between 1 and 50. Output a list of integers as a result of iteratively applying a mathematical function f to the integer var. The function f is defined as f(x)=3x+1 if x is odd and f(x)=x/2 if x is even. Stop the iteration when the value 1 is reached. (Example: When var is 6, the play function’s output sequence should be 6,3,10,5,16,8,4,2,1.) Don’t call any external programs. Implement all algorithms in your script. You may choose whether to define a bash function or not in your script.
Explanation / Answer
!/bin/bash
echo -n "Enter a number between 1 and 50:"
read x
echo $x
while true
do
if [ $x -eq 1 ]
then
break
fi
if [ $(($x%2)) -eq 0 ]
then
x=$(( $x / 2 ))
echo $x
else
x=$(($x*3+1))
echo $x
fi
done
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.