-
-
Save jan-g/ee79303142f0f43dc1d29d55e49e2219 to your computer and use it in GitHub Desktop.
Protohackers primality
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
socat TCP-LISTEN:12345,fork,reuseaddr EXEC:./downstream |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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