Created
November 17, 2012 13:45
-
-
Save retep998/4096084 to your computer and use it in GitHub Desktop.
Number factoring
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdio> | |
#include <ctime> | |
#include <cstring> | |
using namespace std; | |
const size_t s = 0x100; | |
const size_t ss = s * s; | |
size_t * p; | |
bool t[ss] = {}; | |
void prepare() { | |
for (size_t i = 2; i < s; ++i) if (!t[i]) for (size_t j = i * i; j < ss; j += i) t[j] = true; | |
size_t k = 0; | |
for (size_t i = 2; i < ss; ++i) if (!t[i]) ++k; | |
p = new size_t[k]; | |
for (size_t i = 2, j = 0; i < ss; ++i) if (!t[i]) p[j++] = i; | |
} | |
void factor(size_t n) { | |
size_t i = 0; | |
size_t x = n; | |
size_t j = 0; | |
size_t f[0x40]; | |
for (;;) { | |
size_t c = p[i]; | |
size_t d = x / c; | |
size_t r = x % c; | |
if (r) ++i; | |
else { | |
x = d; | |
f[j++] = c; | |
if (x == 1) break; | |
} | |
} | |
size_t m = 1; | |
for (size_t k = 0; k < j; ++k) m *= f[k]; | |
if (m != n) throw; | |
} | |
int main() { | |
clock_t c1 = clock(); | |
prepare(); | |
for (size_t i = 2; i < ss; ++i) factor(i); | |
clock_t c2 = clock(); | |
printf("%u\n", c2 - c1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment