Post Reply 
[HP35s] Program for prime number (Wheel Sieve and Miller-Rabin)
04-13-2019, 06:24 PM (This post was last modified: 10-09-2019 11:08 PM by Albert Chan.)
Post: #54
RE: [HP35s] Program for prime number (Wheel Sieve and Miller-Rabin)
(04-11-2019 03:18 PM)fred_76 Wrote:  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

MOD function is computational expensive.
You can rearrange the formula to reduce MOD count per multiply from 4 to 3

A*B = (xk + y)*(uk v) = (xk uk) (y v) + (y uk v xk)

Base number must be powers of 10, otherwise MOD won't work.
Similarly, IEEE double must pick 2^26 as base, sqrt(2^53-1) ~ 94906266 won't work.
Since (2^26)^2 < 2^53-1, some adjustment is needed for huge IEEE double.

This is my mulmod(a, b, n) Lua code:
PHP Code:
local function mulmod(abn)          -- a*(mod n)
    
local m a*b
    
if <= 2^53 then return m%n end    -- a*b is exact
    
if 4.e31 then a=n-ab=n-b end  -- assume n >= max(a,b)
    
local a2 2^26 2^26
    local b2 
2^26
    a 
a2
    b 
b2
    m 
a*b2 a2*b
    a 
= (a*b)%- (a2*b2)%n         -- = [-n+1,n-1]
    if 
>= 0 then m=m%else - (-m)%n end
    b 
m                       -- = [-n+1,2n-1]
    if 
>= n then return a-n+m end
    
if >= 0 then return else return b+n end
end 

Quote:Prime routine

I used the bases shown here (thank you Albert Chan).

To cover *full* 53 bits IEEE double range, I use above link with 5 best bases.
However, that does not quite reach 53 bits. One simple check pushed it over 53 bits Smile

Snippet from my isprime(n)
PHP Code:
-- Below good for full 53 bits (2^53-9007199254740991). 
-- 
Other "holes"90492034431082519325578861942661971826016842558110064706355310041 ...

return 
issprp(2n)
   and 
issprp(4130806001517n)
   and 
issprp((149795463772692064 n) - 4n)
   and 
issprp((186635894390467040 n) - 3n)
   and 
issprp((3967304179347716096 n) - 291n)
   and 
~= 7999252175582851 

Note that the huge numbers are represented *exactly* in binary.
Also, adjustment (-4,-3,-291) must be negative, to avoid 53-bits overflow.

lua> p = require 'nextprime'
lua> x = 2^53-1
lua> for i=1,10 do x=p.prevprime(x); print(x) end
9007199254740881
9007199254740847
9007199254740761
9007199254740727
9007199254740677
9007199254740653
9007199254740649
9007199254740623
9007199254740613
9007199254740571

Edit: nextprime.lua in https://github.com/achan001/PrimePi
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
RE: [HP35s] Program for prime number (Wheel Sieve and Miller-Rabin) - Albert Chan - 04-13-2019 06:24 PM



User(s) browsing this thread: 12 Guest(s)