The previous program I posted has a bug in that it doesn't generally print the final factor (final value of n). Also, it has an inefficiency in not being bound by the square root of n (which is why it took so long for large primes). Those are fixed below as well as changing it use unsigned long and making it take input from the command line.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h> // sqrtl
#include <errno.h>
typedef unsigned long UL;
void factor(UL n) {
printf("%lu: ", n);
for ( ; n % 2 == 0; n /= 2)
printf("2 ");
UL sq = (UL)sqrtl((long double)n);
for (UL i = 3; i <= sq; ) {
if (n % i == 0) {
printf("%lu ", i);
n /= i;
sq = (UL)sqrtl((long double)n);
}
else
i += 2;
}
if (n > 1)
printf("%lu", n);
putchar('\n');
}
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage: myfactor NUMBER...\n");
exit(EXIT_FAILURE);
}
for (int i = 1; i < argc; i++) {
char *end = NULL;
errno = 0;
UL n = strtoul(argv[i], &end, 10);
if (errno == ERANGE)
fprintf(stderr, "%s: number out of range of unsigned long\n",
argv[i]);
else if (*end)
fprintf(stderr, "%s: invalid number\n", argv[i]);
else if (n != 0)
factor(n);
}
return 0;
}