Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this code for Miller-Rabin test wrong? (answer for the exercise for 1.28 in SICP)

Tags:

scheme

sicp

I was trying to solve exercise 1.28 in SICP, about Miller-Rabin algorithm, after which I found an answer online, but I think the answer was wrong. I come to ask if it's wrong.

He checks if (remainder (square base) m)=1 while doing expmod loops. However, when doing loops the base and m will stay constantly, which means he is doing the same check, and it's not what the Miller-Rabin Test want to do.

(define (expmod base exp m)
  (cond ((= exp 0)
         1)
        ((nontrivial-square-root? base m) 
         0)
        ((even? exp)
         (remainder (square (expmod base (/ exp 2) m))
                    m))
        (else
         (remainder (* base (expmod base (- exp 1) m))
                    m))))

(define (nontrivial-square-root? a n)
  (and (not (= a 1))
       (not (= a (- n 1)))
       (= 1 (remainder (square a) n))))

if n=k*2^c, I think we should check if (remainder (a^(k*2*(c-1))) n)=1.

like image 664
GiAlien Avatar asked Dec 07 '25 06:12

GiAlien


1 Answers

That is what it is supposed to be doing. The procedure expmod is supposed to compute the exponential of a number modulo another number, the only difference this time is that you check for a nontrivial square root every time it recurses. m will stay constant during the expmod procedure, and the miller-rabin procedure you write will run expmod with a random number m every time.

Happy coding!

By the way, good luck with SICP! I'm on excersise 2.45 right now, it gets easier (although there are some very abstract concepts).

like image 68
Jodast Avatar answered Dec 08 '25 20:12

Jodast



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!