In the post " " we saw how we can use the command factor to find whether a number is prime of not. We can extend the same script further to generate all the prime numbers in a given range of numbers.
To generate a range of numbers we can use the command "seq" . The usage of seq is shown in the post " ".
We can use seq in a for loop to iterate over one number at time.
Save the script as seq_for.sh, give it execute permissions and run the script.
Thus we can see that using seq along with for loop we can work on a range of numbers, one number at a time.
This script can be combined with the script in " " to generate all the prime numbers in a range of numbers.
We request the user to enter two numbers to indicate the lower and upper limits of the range of numbers between which the user wants to generate the prime numbers. The lower limit can not be 1 because the number 1 does not have any factors and the command "factor" does not return any thing for 1. Thus we need to make sure the user enters a number bigger than 1. If the user enters 1, then we will prompt the user again to enter number greater than 1.
Then we pass these two numbers to seq in a for loop
In each iteration of the for loop we use the factor command to find out if a number is prime or not.
The full script looks as below.
Save the script as range_prime.sh,give it execute permissions and run it.
Thus we can see the script is able to generate a list of all the prime numbers between 2 and 20.
To generate a range of numbers we can use the command "seq" . The usage of seq is shown in the post " ".
We can use seq in a for loop to iterate over one number at time.
Save the script as seq_for.sh, give it execute permissions and run the script.
Thus we can see that using seq along with for loop we can work on a range of numbers, one number at a time.
This script can be combined with the script in " " to generate all the prime numbers in a range of numbers.
We request the user to enter two numbers to indicate the lower and upper limits of the range of numbers between which the user wants to generate the prime numbers. The lower limit can not be 1 because the number 1 does not have any factors and the command "factor" does not return any thing for 1. Thus we need to make sure the user enters a number bigger than 1. If the user enters 1, then we will prompt the user again to enter number greater than 1.
Then we pass these two numbers to seq in a for loop
In each iteration of the for loop we use the factor command to find out if a number is prime or not.
The full script looks as below.
Save the script as range_prime.sh,give it execute permissions and run it.
Thus we can see the script is able to generate a list of all the prime numbers between 2 and 20.
0 comments:
Post a Comment