查找素数 - 在MacOS上找不到“factor”命令

时间:2013-04-24 16:46:25

标签: macos bash scripting

我正在编写一个bash脚本来查找小于给定整数的所有素数。

以下是代码:

#!/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

我正在使用MacOS,当我执行脚本时,收到此错误消息:

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 

我今天早上开始用bash写作,所以任何帮助都会受到赞赏。我认为这可能与我没有使用Linux的事实有关,但我希望事实并非如此。

4 个答案:

答案 0 :(得分:11)

如评论中所述,因子是GNU coreutils的一部分。您可以使用Homebrew安装coreutils:

brew install coreutils

之后,factor可以替换为脚本中的/usr/local/bin/gfactor

答案 1 :(得分:3)

factor不是标准的Unix命令。 Linux有它。 OS X没有。

答案 2 :(得分:1)

我使用较短的Homebrew安装时出错,但这对我有用:

brew install coreutils findutils gnu-tar gnu-sed gawk gnutls gnu-indent gnu-getopt

答案 3 :(得分:1)

保存此Makefile并运行make。它从NetBSD CVS存储库下载factorprimes的源代码并构建它们。如果您没有curl,请尝试make G=wget

W= http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/games
G= curl -L -R -O
CFLAGS= -Wall -Wextra -O2 -Dlint -D__dead= -DHAVE_OPENSSL

all:    get bin

bin:    factor primes

factor: factor.o pr_tbl.o
    $(CC) -o $@ factor.o pr_tbl.o -lcrypto

primes: primes.o pr_tbl.o pattern.o spsp.o
    $(CC) -o $@ primes.o pr_tbl.o pattern.o spsp.o -lm

clean:
    -rm -f factor primes factor.o pattern.o pr_tbl.o primes.o spsp.o

get:
    $G $W/factor/factor.6
    $G $W/factor/factor.c
    $G $W/primes/pattern.c
    $G $W/primes/primes.6
    $G $W/primes/primes.c
    $G $W/primes/primes.h
    $G $W/primes/pr_tbl.c
    $G $W/primes/spsp.c

(Makefile已更新为包含spsp.c

也可在https://github.com/lhf/factor

获取