[HP35s] Program for prime number (Wheel Sieve and Miller-Rabin)
|
04-11-2019, 03:18 PM
(This post was last modified: 04-11-2019 05:25 PM by fred_76.)
Post: #53
|
|||
|
|||
RE: [HP35s] Program for prime number (brut force)
Here is the code of the MR primality check.
I've been inspired by the post of Thomas Klemm. I haven't used the Gerald H arithmetic library (far too complex to me to understand with all the imbricated XEQs... sorry Gerald). That leaves place for further optimisation. Modular addition Here we reduce first A to A≡N and B to B≡N then calculate A-N+B (which can't overflow) ≡ N we could save a calculation of A-N if A+B does not overflow, but the test takes longer than the substraction A-N. Code: Line Code Comment Exemple of use : RCL A RCL B RCL N XEQ A returns (A+B)≡N in X and N in Last X (y z t contain rubbish) Modular multiplication Based on the fact that if you write : A = xk+y B = uk+u where k is a base number, I took k = (999 999 999 999)^0.5 = 1 000 000 Then A*B = (xk+y)*(uk+v) = xuk²+xvk+yuk+yv or better = k(xuk+xv+yu)+yv A*A = x²k²+xyk+xyk+y² = k(x²k+xy+xy)+y² Note that you can't use directly 2xyk as it sometimes overflows. The code is slightly more complex as it treats differently the case (AxB)≡N and (AxA)≡N for speed. Code: Line Code Comment Exemple of use : RCL A RCL B RCL N XEQ B returns (A*B)≡N in X and N in Last X (y z t contain rubbish) Modular exponentiation This one is the regular "right-to-left" modular exponentiation. Code: Line Code Comment Exemple of use : RCL A RCL B RCL N XEQ C returns (A^B)≡N in X (yzt and last x contain rubbish) Check if composite As explained here. Code: Line Code Comment Prime routine I used the bases shown here (thank you Albert Chan). Code: Line Code Comment Exemple of use : RCL N XEQ E shows P= N if N is Prime shows C= N if N is Composite the flags 1-2-3-4 show the status of the calculations (4 bases max) so you see where it is the flag 0 is used by the modular multiplication, it blinks so that you know it did not freeze :-) One could go slightly faster by storing the constants that are used several times in variables (like 1000000, 1 and 2). Adding brut force to find factors of for "small numbers" 1) I have also merged the "brut force" with the "MR" so that numbers smaller than 20 359 000 will be analysed by brut force, and greater by MR, because MR is slower than brut force for numbers smaller than 20 359 000. 2) When a number is found to be composite, it goes to brut force to find factors. When a factor is found, the quotient is sent back to MR to check if it is composite or prime, and so on. Brut force is however very slow to find factors if they are big. For example it takes only 34s for MR to say 999 999 998 479 is composite, but 2h30 for Brut Force to find its factors... Fred |
|||
« Next Oldest | Next Newest »
|
User(s) browsing this thread: 19 Guest(s)