From 3e8b8b9ff4e818c0224e932451ef5cf5fa958545 Mon Sep 17 00:00:00 2001 From: Rawiri Blundell Date: Fri, 14 Oct 2016 21:10:50 +1300 Subject: [PATCH] Updated SC2039 (markdown) --- SC2039.md | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/SC2039.md b/SC2039.md index c92ab18..b3a6bb2 100644 --- a/SC2039.md +++ b/SC2039.md @@ -57,6 +57,60 @@ POSIX: while [ $((test)) -ne 0 ]; do foo; : $((next)); done ``` +### Arithmetic exponentiation + +Bash: + +```Bash +printf "%s\n" "$(( 2**63 ))" +``` + +POSIX: + +The POSIX standard does not allow for exponents. However, you can replicate them completely built-in using a POSIX compatible function. As an example, the `pow` function from [here](http://unix.stackexchange.com/a/7925). + +```sh +pow () { + set $1 $2 1 + while [ $2 -gt 0 ]; do + set $1 $(($2-1)) $(($1*$3)) + done + echo $3 +} +``` + +To compare: + +```sh +$ echo "$(( 2**62 ))" +4611686018427387904 +$ pow 2 62 +4611686018427387904 +``` + +Alternatively, if you don't mind using an external program, you can use `bc`. Be aware though: `bash` and other programs may abide by a certain maximum integer that `bc` does not (for `bash` that's: 64-bit signed long int, failing back to 32-bit signed long int). + +Example: + +```Bash +# Note the overflow that gives a negative number +$ echo "$(( 2**63 ))" +-9223372036854775808 + +# No such problem +$ echo 2^63 | bc +9223372036854775808 + +# 'bc' just keeps on going +$ echo 2^1280 | bc +20815864389328798163850480654728171077230524494533409610638224700807\ +21611934672059602447888346464836968484322790856201558276713249664692\ +98162798132113546415258482590187784406915463666993231671009459188410\ +95379622423387354295096957733925002768876520583464697770622321657076\ +83317005651120933244966378183760369413644440628104205339687097746591\ +6057756101739472373801429441421111406337458176 +``` + ### standalone `((..))` Bash: