-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathexponent.fth
More file actions
36 lines (32 loc) · 1.01 KB
/
exponent.fth
File metadata and controls
36 lines (32 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
\ Copyright 2017 Fredrik Noring
require math/modulo.fth
\ Compute -1 n **.
: -1swap** ( n -- n ) 1 and 1 lshift 1 swap - ;
\ Integer exponentiation function. Note that in Forth with negative bases and
\ exponents the result is implementation defined, because the division quotient
\ may be rounded to either negative infinity (floored division) or rounded
\ towards zero (symmetric division).
: ** ( n1 n2 -- n3 )
1 { b e r }
e 0< if
b 0= if abort" Division by zero." then
1 b e negate recurse /
else
begin e ( Fast exponentiation by squaring. )
while e 1 and if r b * to r then
b b * to b
e 1 rshift to e
repeat r
then ;
\ Modular exponentiation function.
: **mod ( n1 n2 n3 -- n4 )
1 { b e m r }
e 0< if
abort" Inverse modular exponentiation not implemented."
else
begin e ( Fast exponentiation by squaring. )
while e 1 and if r b m *mod to r then
b b m */mod drop to b
e 1 rshift to e
repeat r
then ;