Fast remainder
|
05-12-2021, 11:03 PM
(This post was last modified: 05-13-2021 10:26 PM by Albert Chan.)
Post: #6
|
|||
|
|||
RE: Fast remainder
(05-12-2021 03:10 PM)Albert Chan Wrote: If n = 128 = 2^7, then log2(d) < 7 Instead of using general rule, we can get more closely to the fastmod limit. M = 2^F - 1 c = floor(M/d) + 1 = (M+1)/d + (d-1-M%d)/d = 2^F/d + cerr fastmod(x, d, c) = floor((x*c & M) * d / (M+1)) For fastmod to work, x must not be too big to cause error ≥ 1, where floor cannot correct. x * cerr * d / (M+1) < 1 x * (d-1 - M%d) ≤ M max(x) = floor(M / (d-1 - M%d)) Note that max(x) goes infinite when RHS denominator goes 0, when d = pow-of-2. To confirm the equation, lets redo previous post examples, by direct calculation. >>> M = (1<<32) - 1 # F = 32 >>> maxx = lambda d: int(M // (d-1 - M%d)) >>> print hex(maxx(17)), hex(maxx(29)) 0xfffffff 0x13b13b13 Now, we are ready to get closer fastmod limit. Code: for n in range(128, 256): max base = 217 Actually, looping it all is unnecessary. We maximize denominator (assume M%d=0), replace integer divide with float divide. 2*n^3 = M / (n-2) n ≈ 4√(M/2) ≈ 215.3 Consider effect of n-2 ≈ n, this is below solution for actual n. Start from n=216, we hit the sweet spot in 3 tries (n=218 failed max(x) test) --- This is the patch to code (post #2) For n=60, timing goes from 14.5 sec, down to 12.3 sec. Code: 33c33 |
|||
« Next Oldest | Next Newest »
|
Messages In This Thread |
Fast remainder - Albert Chan - 05-09-2021, 08:48 PM
RE: Fast remainder - Albert Chan - 05-10-2021, 02:44 PM
RE: Fast remainder - Albert Chan - 05-12-2021, 12:05 AM
RE: Fast remainder - Albert Chan - 05-12-2021, 03:10 PM
RE: Fast remainder - Albert Chan - 05-12-2021 11:03 PM
RE: Fast remainder - Albert Chan - 05-12-2021, 04:12 PM
RE: Fast remainder - Albert Chan - 05-14-2021, 06:15 PM
|
User(s) browsing this thread: 1 Guest(s)