Simple bash script to print prime numbers from 1 to 1000
5,097
factor {2..1000} | awk 'NF==2{print $2}'
Related videos on Youtube
Author by
FranceskaSophie
Updated on September 18, 2022Comments
-
FranceskaSophie almost 2 years
How can I make a POSIX script that will print all the prime numbers from 1 to 1000?
-
Shadur over 8 yearsYou'll want python or perl for that, bash isn't exactly a good choice for math stuff.
-
Allan over 8 yearsThis sounds like something you needed for a class. Shouldn't you have at least made an initial attempt yourself and ask for assistance rather than just asking outright for the answer? How do you move forward from newbie if you don't try?
-
Stéphane Chazelas over 5 years@Shadur, the OP asked for a POSIX script, not
bash
. POSIX comes with several utilities that can be used as script interpreters likeawk
,bc
,sh
,sed
.awk
andbc
are perfectly suited for the task or could be invoked from ash
script. A shell is primarily a command line interpreter, so if any command can do the task, any shell script that invokes that command (which could by perl or python) would work.
-
-
FranceskaSophie over 8 yearsThanks for the reply! Helped me a lot, but I'm not quite sure how to interpret that code. Would you care to explain to me how it works? I was thinking of using a "for"
-
orion over 8 yearsThe point of a shell is to glue together existing pieces of purpose made things that do one thing, and do it well. In this case, I'm calling
factor
which factorizes numbers andawk
is there just to filter the output (only print if there is only one factor). If your goal was to write the prime algorithm from scratch, then you'll probably have loops and such. But that, you can try for yourself. -
Stéphane Chazelas over 5 years
factor
is not a POSIX command.