Skip to content

Instantly share code, notes, and snippets.

@JackZielke
Last active February 26, 2022 16:57
Show Gist options
  • Select an option

  • Save JackZielke/eebcf533fd7d421d563e6174c98e17f2 to your computer and use it in GitHub Desktop.

Select an option

Save JackZielke/eebcf533fd7d421d563e6174c98e17f2 to your computer and use it in GitHub Desktop.
Help find prime numbers for Primel https://converged.yt/primel/
#!/bin/bash
if test ! -e 5_digit_primes.txt.xz; then
echo 5_digit_primes.txt.xz does not exist
echo $0 requires this file
echo Please generate it with the following command
echo "seq 10007 99991|factor|grep '^\([^:]*\): \1$'|cut -d: -f1|xz -9e >5_digit_primes.txt.xz"
exit 2
fi
if test -z "$REG" -a -z "$XREG" -a -z "$SKIP"; then
echo Start with 25693
echo
echo Examples:
echo REG=..491 XREG=3.... SKIP=256870 $0
echo
echo REG=9.... XREG=.[35]5.3 SKIP=2681 $0
echo
echo 'REG = regex search - correct numbers'
echo XREG = regex remove - misplaced numbers
echo SKIP = numbers to remove - not in answer
exit 1
fi
COMMAND='xzcat 5_digit_primes.txt.xz'
if test -n "$REG"; then
COMMAND+="|grep ^$REG"
fi
if test -n "$XREG"; then
KEEP="$(echo $XREG|tr -d '.[]^'|fold -w1|sort -u |tr -d '\n')"
SEARCH=
for ((i=1;i<=${#XREG};i++)); do
if test "${XREG:$i-1:1}" = '['; then
SEARCH+='[^'
((i++))
while test "${XREG:$i-1:1}" != ']'; do
SEARCH+="${XREG:$i-1:1}"
((i++))
done
SEARCH+=']'
elif test "${XREG:$i-1:1}" != '.'; then
SEARCH+='[^'${XREG:$i-1:1}']'
else
SEARCH+=.
fi
done
if test -n "$SEARCH"; then
COMMAND+="|grep -E '$SEARCH'"
fi
fi
if test -n "$KEEP"; then
COMMAND+="|awk '"
for ((i=1;i<=${#KEEP};i++)); do
COMMAND+="/${KEEP:$i-1:1}/"
if test $i -ne ${#KEEP}; then
COMMAND+=' && '
fi
done
COMMAND+="'"
fi
if test -n "$SKIP"; then
PSKIP=$(echo $SKIP|sed 's/\B/|/g')
COMMAND+="|grep -Ev '$PSKIP'"
fi
eval $COMMAND
@JackZielke

JackZielke commented Feb 26, 2022 •

Copy link
Copy Markdown
Author

I don't think I would do it, but since the prime numbers are generated so quickly and everything is done in 1 pass, you could generate them on the fly each time and save 8k of disk space. To do this, delete (or comment out) lines 3 through 9. Replace the old line 25

COMMAND='xzcat 5_digit_primes.txt.xz'

with

COMMAND="seq 10007 99991|factor|grep '^\([^:]*\): \1$'|cut -d: -f1"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment