4

我正在编写一个 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

4 回答 4

14

正如评论中提到的,因素是 GNU coreutils 的一部分。您可以使用Homebrew安装 coreutils :

brew install coreutils

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

于 2013-04-25T06:37:43.193 回答
3

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

于 2013-04-24T16:49:12.873 回答
1

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

brew install coreutils findutils gnu-tar gnu-sed gawk gnutls gnu-indent gnu-getopt
于 2014-01-31T06:57:20.980 回答
1

保存Makefile并运行make。它从 NetBSD CVS 存储库下载源代码factor并构建它们。primes如果没有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

于 2014-07-02T16:37:14.190 回答