Write a bash script that accepts one command line argument a which is an integer
ID: 3823419 • Letter: W
Question
Write a bash script that accepts one command line argument a which is an integer between 1 and 50. Output a list of integers starting from a and ending with 1 according to the rule you are already familiar with (f(x)=x/2 if x is even; f(x)=3x+1 if x is odd). Don’t call any external programs. Implement all algorithms in your script.
This is what ive tried and I cant get it to work.
#!/bin/bash
arg = 0;
while [ $arg -lt 51 ];
do
if ((arg%2==0)); then
((arg=arg/2))
elif((arg%2!=0)); then
((arg=(3*arg)+1))
fi
echo $arg
done
Explanation / Answer
1. In the while loop, you need to check when to stop running the program. You need to end the loop with value 1.
So please change the while statement as below:
while [ $arg -gt 1 ];
As soon as value 1 is reached, it should stop.
2. Also when you are assigning the value to arg prior to the loop, there should be no spaces. Semicolon is also not needed for this assignment statement.
In this program you have tested it with value 0. Test it with numbers between 1 and 50.
3. Below are some sample test results after doing the above changes:
TEST 1 with 10
#!/bin/bash
arg=10
while [ $arg -gt 1 ];
do
if ((arg%2==0)); then
((arg=arg/2))
elif((arg%2!=0)); then
((arg=(3*arg)+1))
fi
echo $arg
done
Output is as below
5
16
8
4
2
1
As seen here first 10 is halved and it displays 5 then it is 3x+1 as this is odd number. Following that 16 is repeatedly halved until 1 is reached.
Test 2 with 7
#!/bin/bash
arg=7
while [ $arg -gt 1 ];
do
if ((arg%2==0)); then
((arg=arg/2))
elif((arg%2!=0)); then
((arg=(3*arg)+1))
fi
echo $arg
done
Output is as below
22
11
34
17
52
26
13
40
20
10
5
16
8
4
2
1
As 7 is odd, output is trippled and 1 is added. Then it is halved to 11 and it continues till 1 is reached.
Test 3 with 5
#!/bin/bash
arg=5
while [ $arg -gt 1 ];
do
if ((arg%2==0)); then
((arg=arg/2))
elif((arg%2!=0)); then
((arg=(3*arg)+1))
fi
echo $arg
done
Output is as below
16
8
4
2
1
Test 4 with 48
#!/bin/bash
arg=48
while [ $arg -gt 1 ];
do
if ((arg%2==0)); then
((arg=arg/2))
elif((arg%2!=0)); then
((arg=(3*arg)+1))
fi
echo $arg
done
Output is as below
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.