Skip to content

Instantly share code, notes, and snippets.

@funny-falcon
Last active December 19, 2024 09:44
Show Gist options
  • Save funny-falcon/173923b4fea7ffdf9e02595a0f99aa74 to your computer and use it in GitHub Desktop.
Save funny-falcon/173923b4fea7ffdf9e02595a0f99aa74 to your computer and use it in GitHub Desktop.
Compare division module with module by reciprocal
#include <stdlib.h>
#include <stdio.h>
#include <inttypes.h>
#include <math.h>
static inline uint32_t
div_mult(uint32_t n, uint32_t d, uint32_t r)
{
uint64_t m = (uint64_t)n*r;
return n - d*(m>>32);
}
static inline uint32_t
div_div(uint32_t n, uint32_t d)
{
return n % d;
}
static inline uint32_t
div_and(uint32_t n, uint32_t d)
{
return n & (d-1);
}
int
main(int argc, char** argv)
{
uint32_t n = argc > 1 ? atoi(argv[1]) : 100000;
uint32_t D = argc > 2 ? atoi(argv[2]) : 1024;
uint32_t m = argc > 3 ? atoi(argv[3]) : 2;
uint32_t d,r,i;
uint64_t s = 0;
for (d = 2; d <= D; d++)
{
r = ceil((double)(1ll<<32)/d);
if (m == 0)
{
for (i = 0; i < n; i++)
s += div_div(i + s, d);
}
else if (m == 1)
{
for (i = 0; i < n; i++)
s += div_mult(i + s, d, r);
}
else if (m == 2)
{
for (i = 0; i < n; i++)
{
s = div_div(i, d);
if (s == div_mult(i, d, r))
continue;
printf("d:%u i:%u r:%u dd:%u dm:%u\n",
d, i, r, (uint32_t)s, div_mult(i, d, r));
break;
}
}
else if (m == 3)
{
for (i = 0; i < n; i++)
s += div_and(i + s, d);
}
}
printf("%llu\n", (long long)s);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment