Skip to content

Commit 0c2fa43

Browse files
Doc Mopavpanchekha
authored andcommitted
negative exponents allowed in modular-expt
1 parent 3409a8e commit 0c2fa43

File tree

3 files changed

+9
-2
lines changed

3 files changed

+9
-2
lines changed

math-doc/math/scribblings/math-number-theory.scrbl

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -175,12 +175,13 @@ This function is also known as the @emph{Legendre symbol}.
175175

176176
@defproc[(modular-expt [a Integer] [b Integer] [n Integer]) Natural]{
177177
Computes @racket[(modulo (expt a b) n)], but much more efficiently. The modulus @racket[n] must
178-
be positive, and the exponent @racket[b] must be nonnegative.
178+
be positive.
179179

180180
@examples[#:eval untyped-eval
181181
(modulo (expt -6 523) 19)
182182
(modular-expt -6 523 19)
183183
(modular-expt 9 158235208 19)
184+
(modular-expt 2 -1 11)
184185
(eval:alts (code:line (code:comment "don't try this at home!")
185186
(modulo (expt 9 158235208) 19))
186187
(eval:result @racketresultfont{4}))

math-lib/math/private/number-theory/modular-arithmetic-base.rkt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@
4848
(: modular-expt* (Positive-Integer Integer Integer -> Natural))
4949
;; Exponentiate by repeated modular multiplication and squaring
5050
(define (modular-expt* n a b)
51-
(cond [(b . < . 0) (raise-argument-error 'modular-expt "Natural" 1 a b n)]
51+
(cond [(b . < . 0) (modular-expt* n (modular-inverse* n a) (- b))]
5252
[(b . = . 0) (if (n . = . 1) 0 1)]
5353
[else
5454
(let ([a (modulo a n)])

math-test/math/tests/number-theory-tests.rkt

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,12 @@
253253
(check-equal? (with-modulus 7 (mod/ 1 3)) 5)
254254
(check-equal? (with-modulus 7 (mod/ 3)) 5)
255255

256+
(check-equal? (modular-expt 2 8 11) 3)
257+
(check-equal? (modular-expt 2 -1 19) 10)
258+
(check-equal? (modular-expt 3 -2 47) 21) ; PowerMod[3,-2,47]
259+
(check-equal? (modular-expt 3 -4 47) 18) ; PowerMod[3,-4,47]
260+
261+
(check-equal (with-modulus 19 (modexpt 2 -1)) 10)
256262

257263
; "quadratic-residues.rkt"
258264
(check-equal? (quadratic-character 2 5) -1)

0 commit comments

Comments
 (0)