Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding Prime Numbers - "factor" command not found on MacOS

I am writing a bash script to find all of the prime numbers less than a given integer.

Here is the code:

#!/bin/bash

BADARGS=65
if [ -z $1 ]
then
   echo "Usage:`basename $0` cannot have a null parameter."
   exit $BADARGS
elif [ $1 -lt 2 ]
then
   echo "Usage:`basename $0` should have the value 2 or more as the parameter."
   exit $BADARGS
fi
TRUE=0
FALSE=
Primes(){
checkPrime=( $(factor $1) ) # this puts factors into array

if [ -z "${checkPrime[2]}" ] # third element is null
then
   return $TRUE
else
   return $FALSE
fi
}
printf "2 "
let "n = 3"
while [ $n -le $1 ]
do
   if Primes $n
   then
       printf "$n "
   fi
       let "n += 2"   
done
printf "\n"

# END

I am using MacOS and when I execute the script I receive this error message:

Jessicas-MacBook-Pro:Documents jessicalott$ ./primes.sh 10
2 ./primes.sh: line 16: factor: command not found
3 ./primes.sh: line 16: factor: command not found
5 ./primes.sh: line 16: factor: command not found
7 ./primes.sh: line 16: factor: command not found
9 

I literally starting writing in bash this morning so any help would be appreciated. I think it might have something to do with the fact that I am not using Linux, but I hope that is not the case.

like image 520
JLott Avatar asked Nov 30 '22 21:11

JLott


2 Answers

factor is not a standard Unix command. Linux has it. OS X does not.

like image 27
Eric Postpischil Avatar answered Dec 04 '22 05:12

Eric Postpischil


As mentioned in a comment, factor is part of GNU coreutils. You can install coreutils with Homebrew:

brew install coreutils

After that factor can be replaced with /usr/local/bin/gfactor in the script.

like image 66
Lri Avatar answered Dec 04 '22 03:12

Lri