// Prime factors.
#include <stdlib.h>
#include <stdio.h>
#define ARRAY_MAX_SIZE 100
#define ARRAY_INITIALIZER ((struct array) {{}, 0})
struct array {
int p[ARRAY_MAX_SIZE]; size_t n;
};
void append(struct array *a, int i)
{
if (a->n < ARRAY_MAX_SIZE) {
a->p[a->n++] = i;
} else {
fprintf(stderr
, "overflow in %s", __func__
); }
}
void print(const struct array *a, int end)
{
for (size_t i = 0; i < a->n; i++)
printf("%s%d", i
? ", " : "", a
->p
[i
]); if (end != 0)
}
void factor(int n, struct array *r)
{
for (int i = 2; i*i <= n; i++) {
while (n%i == 0) {
append(r, i);
n = n/i;
}
}
if (n > 1)
append(r, n);
}
int main(void)
{
struct array r = ARRAY_INITIALIZER;
factor(2*3*5*7*11*13*17*19*23, &r);
print(&r, '\n');
r = ARRAY_INITIALIZER;
factor(0x80000, &r);
print(&r, '\n');
r = ARRAY_INITIALIZER;
factor(0x7FFFF, &r);
print(&r, '\n');
return 0;
}
Ly8gUHJpbWUgZmFjdG9ycy4KCiNpbmNsdWRlIDxzdGRsaWIuaD4KI2luY2x1ZGUgPHN0ZGlvLmg+CgojZGVmaW5lIEFSUkFZX01BWF9TSVpFIDEwMAojZGVmaW5lIEFSUkFZX0lOSVRJQUxJWkVSICgoc3RydWN0IGFycmF5KSB7e30sIDB9KQoKc3RydWN0IGFycmF5IHsKICAgIGludCBwW0FSUkFZX01BWF9TSVpFXTsgc2l6ZV90IG47Cn07Cgp2b2lkIGFwcGVuZChzdHJ1Y3QgYXJyYXkgKmEsIGludCBpKQp7CiAgICBpZiAoYS0+biA8IEFSUkFZX01BWF9TSVpFKSB7CiAgICAgICAgYS0+cFthLT5uKytdID0gaTsKICAgIH0gZWxzZSB7CiAgICAgICAgZnByaW50ZihzdGRlcnIsICJvdmVyZmxvdyBpbiAlcyIsIF9fZnVuY19fKTsKICAgICAgICBleGl0KEVYSVRfRkFJTFVSRSk7CiAgICB9Cn0KCnZvaWQgcHJpbnQoY29uc3Qgc3RydWN0IGF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