Skip to content

Instantly share code, notes, and snippets.

@beyondlimits
Last active August 4, 2019 21:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beyondlimits/6392c03f82d694c7ebbde0cc593441ce to your computer and use it in GitHub Desktop.
Save beyondlimits/6392c03f82d694c7ebbde0cc593441ce to your computer and use it in GitHub Desktop.
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#define LOG_2 0x02000000
#define LOG_3 0x032B8034
#define LOG_5 0x04A4D3C2
#define LOG_7 0x059D5D9F
#define LOG_LIMIT 0x80000000
#define COUNT 85348
static unsigned long long numbers[COUNT];
static int comparelongs(const void *a, const void *b)
{
if ((*(unsigned long long*)a) > (*(unsigned long long*)b)) {
return 1;
}
if ((*(unsigned long long*)a) < (*(unsigned long long*)b)) {
return -1;
}
return 0;
}
static void initialize(unsigned long long *array)
{
unsigned l2, l3, l5, l7, count;
unsigned long long x2, x3, x5, x7;
for (
l2 = 0, x2 = 1, count = 0;
l2 < LOG_LIMIT;
l2 += LOG_2, x2 *= 2
) {
for (
l3 = l2, x3 = x2;
l3 < LOG_LIMIT;
l3 += LOG_3, x3 *= 3
) {
for (
l5 = l3, x5 = x3;
l5 < LOG_LIMIT;
l5 += LOG_5, x5 *= 5
) {
for (
l7 = l5, x7 = x5;
l7 < LOG_LIMIT;
l7 += LOG_7, x7 *= 7
) {
assert(count < COUNT);
array[count] = x7;
++count;
}
}
}
}
assert(count == COUNT);
qsort(array, count, sizeof(*array), comparelongs);
}
unsigned long long find(unsigned long long x)
{
int a = 0, b = COUNT;
do {
int c = (a + b) / 2;
if (numbers[c] > x) {
b = c;
} else {
a = c;
}
} while (b - a > 1);
return numbers[a] > x ? numbers[a] : numbers[b];
}
int main(int argc, char *argv[])
{
if (argc < 2) {
exit(EXIT_FAILURE);
}
initialize(numbers);
int i;
for (i = 1; i < argc; ++i) {
unsigned long long x = atoll(argv[i]);
printf("%Lu %Lu\n", x, find(x));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment