Download code

Jump to: navigation, search

Back to Exponentiation_by_squaring_(AWK/dc)

Download for Windows: single file, zip

Download for UNIX: single file, zip, tar.gz, tar.bz2

expbysqr.awk

 1 #!/usr/bin/awk -f
 2 # The authors of this work have released all rights to it and placed it
 3 # in the public domain under the Creative Commons CC0 1.0 waiver
 4 # (http://creativecommons.org/publicdomain/zero/1.0/).
 5 # 
 6 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 7 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 8 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 9 # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
10 # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
11 # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
12 # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
13 # 
14 # Retrieved from: http://en.literateprograms.org/Exponentiation_by_squaring_(AWK/dc)?oldid=19118
15 
16 BEGIN                           { FS="^" }
17 $1 ~ /[0-9]+/ && $2 ~ /[0-9]+/  { exponentiate($1,$2); next }
18 BEGIN                           { print "enter expressions of the form i^j" }
19 function genexpr(a,b) {
20     e = "p"
21     for(;;) {
22         if(b < 2) {
23                        if(b % 2)  e = a " " e
24 	               else       e = 1 " " e
25             return e
26         }
27                 if(b % 2)      e = "d*" a "*" e
28 	        else           e = "d*"       e
29         b = int(b/2)
30     }
31 }
32 function exponentiate(a,b)      { print genexpr(a,b) | "dc" }
33 


hijacker
hijacker
hijacker
hijacker