Simple bash script to print prime numbers from 1 to 1000

5,097
factor {2..1000} | awk 'NF==2{print $2}'
Share:
5,097

Related videos on Youtube

FranceskaSophie
Author by

FranceskaSophie

Updated on September 18, 2022

Comments

  • FranceskaSophie
    FranceskaSophie almost 2 years

    How can I make a POSIX script that will print all the prime numbers from 1 to 1000?

    • Shadur
      Shadur over 8 years
      You'll want python or perl for that, bash isn't exactly a good choice for math stuff.
    • Allan
      Allan over 8 years
      This 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
      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 like awk, bc, sh, sed. awk and bc are perfectly suited for the task or could be invoked from a sh 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
    FranceskaSophie over 8 years
    Thanks 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
    orion over 8 years
    The 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 and awk 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
    Stéphane Chazelas over 5 years
    factor is not a POSIX command.