Miller–Rabin primality test: Difference between revisions

→‎{{header|Fortran}}: When generating X**P via repeated squarings of W, square W only if more power is needed. The resulting code loses DO WHILE and has a GO TO...
(→‎{{header|Fortran}}: When generating X**P via repeated squarings of W, square W only if more power is needed. The resulting code loses DO WHILE and has a GO TO...)
Line 1,382:
INTEGER FUNCTION MODEXP(N,X,P) !Calculate X**P mod N without overflowing...
C Relies on a.b mod n = (a mod n)(b mod n) mod n
INTEGER N,X,P !All presumed positive, and X < N.
INTEGER I !A stepper.
INTEGER*8 V,W !Broad scratchpads, otherwise N > 46340 may incur overflow in 32-bit.
V = 1 !=X**0
IF (P.GT.0) THEN !Something to do?
W = X !=X**1, X**2, X**4, X**8, ... except, all are mod N.
I = P !AYes. Get a copy I can mess with.
DO WHILE (I.GT.0)W = X !Any=X**1, bitsX**2, ofX**4, powerX**8, left?... except, all are mod N.
1 IF (MOD(I,2).EQ.1) V = MOD(V*W,N) !Yes.Incorporate AtW if the low -end? calls for it.
WI = MOD(W**I/2,N) !Square W readyUsed. forShift the next bitone updown.
IF (I.GT.0) = I/2 THEN !ShiftStill that bitsomething to the low order end.do?
END DO W = MOD(W**2,N) !OnYes. toSquare W ready for the next bit of the powerup.
MODEXP = V !Done, in lb(P)GO iterationsTO 1 !Consider it.
END IF !Don't square W if nothing remains. It might overflow.
END IF !Negative powers are ignored.
MODEXP = V !Done, in lb(P) iterations!
END FUNCTION MODEXP !"Bit" presence by arithmetic: works for non-binary arithmetic too.
END MODULE MRTEST !Just some trial versions.
 
PROGRAM POKEMR
1,220

edits