Fast remainder
|
05-09-2021, 08:48 PM
(This post was last modified: 05-12-2021 11:46 PM by Albert Chan.)
Post: #1
|
|||
|
|||
Fast remainder
This thread is inspired by thread: Puzzle - RPL and others
We extended the search not just to decimal, but base n, and allowed diigts 1 .. n-1 One of the hot spot is the expensive (mod k) operation. Updated code unroll loops to reduce expensive modulo. (this cut down modulo to 1/6th, with reduce n domain, 0 < n ≤ 190) d = ((((((d*n + X[i])*n + X[i+1])*n + X[i+2])*n + X[i+3])*n + X[i+4])*n + X[i+5]) % k I just learned another way, by replacing modulo with 2 multiply and shift. (Python infinite precision integer need masking M step; C code get this for free.) It go straight for remainder, and not waste time computing quotient. Below setup is for 0 ≤ x ≤ 2**16 = 65536 >>> M = 0xffffffff >>> def mod17(x, c = M//17+1): return (x*c & M) * k >> 32 ... >>> print mod17(12345), 12345 % 17 3 3 Code: #include <stdio.h> >polydivisible 2 { 1 } >polydivisible 4 { 1 2 3 } { 3 2 1 } >polydivisible 6 { 1 4 3 2 5 } { 5 4 3 2 1 } >polydivisible 8 { 3 2 5 4 1 6 7 } { 5 2 3 4 7 6 1 } { 5 6 7 4 3 2 1 } >polydivisible 10 { 3 8 1 6 5 4 7 2 9 } >polydivisible 12 >polydivisible 14 { 9 12 3 10 5 4 7 6 11 8 1 2 13 } For n=60 (no solution): % take 114 sec., fastmod take 58 sec, 114/58 = 2.0X Reference: Faster remainders when the divisor is a constant: beating compilers and libdivide And, for finer points, More fun with fast remainders when the divisor is a constant Update: I messed up the code (now fixed) I had forgotten fastmod required very wide bits to work. For 64-bits machine, fastmod arguments is limited to 16-bits. This prevented any unrolling (and still use 1 fastmod per loop) 2*(n-1)*n < 2^16 → Base n ≤ 181 |
|||
« 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)