Skip to content

Instantly share code, notes, and snippets.

@jan-g
Created October 21, 2022 10:23
Show Gist options
  • Save jan-g/ee79303142f0f43dc1d29d55e49e2219 to your computer and use it in GitHub Desktop.
Save jan-g/ee79303142f0f43dc1d29d55e49e2219 to your computer and use it in GitHub Desktop.
Protohackers primality
#!/bin/bash
debug() {
echo "$@" >&2
}
while IFS= read -r line || [[ -n "$line" ]]
do
req="$(<<<"$line" jq -c .)"
debug "input: $req"
if [[ $? != 0 ]]; then
debug " malformed json"
echo '{}'
exit
fi
wellformed="$(<<<"$req" jq -c '
(.method == "isPrime") and (.number | type == "number")
')"
if [[ "$wellformed" != true ]]; then
debug " not well formed"
echo '{}'
exit
fi
debug " well formed"
number="$(<<<"$req" jq -c '
def isInteger:
(. | type == "number") and
(. | floor == .)
;
if (.number | isInteger) and (.number > 1) then
.number
else
0
end
')"
prime="$(openssl prime -- "$number" | grep -v 'is not')"
if [[ -n "$prime" ]]; then
debug " prime: $number"
echo '{"method": "isPrime", "prime": true}'
else
debug " not prime: $number"
echo '{"method": "isPrime", "prime": false}'
fi
done
#!/bin/sh
socat TCP-LISTEN:12345,fork,reuseaddr EXEC:./downstream
This has a performance problem with the multiclient tests on the host I run it on.
I initially used an alternative jq-only naive primality test - this was too slow as well, so I dropped into openssl's checker.
```
# replace from `number=`
<<<"$req" jq -c '
def isInteger:
(. | type == "number") and
(. | floor == .)
;
def isFactor($f):
if $f * $f > . then
false
elif . % $f == 0 then
true
else
isFactor($f + 1)
end
;
def isPrime:
if . < 2 then
false
else
isFactor(2)
end
;
{ method: "isPrime",
prime: ((.number | isInteger) and (.number | isPrime)) }
'
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment