Skip to content

Instantly share code, notes, and snippets.

@greymd
Last active November 15, 2016 11:36
Show Gist options
  • Select an option

  • Save greymd/17ed59a90f60772447a13ec5aa14f509 to your computer and use it in GitHub Desktop.

Select an option

Save greymd/17ed59a90f60772447a13ec5aa14f509 to your computer and use it in GitHub Desktop.
Power operation by Shell Script
#!/bin/bash
# Usage
# $ pow.sh x n
# result = x^n
calc () {
echo "$1" | bc | tr -dc '[-0-9]'
}
P=$1
N=$2
V=1
while ([ "$N" != "0" ]); do
[ "$(calc "$N%2")" = "1" ] && V=$(calc "$V*$P")
N=$(calc "$N/2")
P=$(calc "$P*$P")
done
echo "$V"
### Check result
# $ ruby -e 'print 12345 ** 4321' | tr -dc '0-9' | openssl dgst -md5
# 92fbfa2dd3aac1339d81440853cf036c
# $ pow 12345 4321 | tr -dc '0-9' | openssl dgst -md5
# 92fbfa2dd3aac1339d81440853cf036c
### Speed
# $ time bash -c "ruby -e 'print 12345 ** 4321'" 1>/dev/null
# bash -c "ruby -e 'print 12345 ** 4321'" > /dev/null 0.49s user 0.37s system 89% cpu 0.955 total
# $ time bash -c 'pow 12345 4321' 1>/dev/null
# bash -c 'pow 12345 4321' > /dev/null 0.33s user 0.30s system 160% cpu 0.393 total
# $ time bash -c "echo 'print pow(12345,4321)' | python" >/dev/null
# bash -c "echo 'print pow(12345,4321)' | python" > /dev/null 0.03s user 0.02s system 89% cpu 0.047 total
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment