/* Find the prime factors of positive integers. The numbers are given on the command line or standard input (one to a line). The output is of the form number=factor*factor*factor. Naive algorithm. (It's fast enough.) */ #include #include #include #include #include #include unsigned long smallest_divisor(unsigned long n) { unsigned long i; unsigned long limit = (unsigned long) sqrt(n); if (n <= 2) return n; if (2 <= limit && n % 2 == 0) return 2; if (3 <= limit && n % 3 == 0) return 3; for (i = 5; i <= limit; i += 6) { if (n % i == 0) return i; if (n % (i + 2) == 0) return i + 2; } return n; } static void factor(const char *number) { char *end; unsigned long n = (errno = 0, strtoul(number, &end, 10)); if (n == ULONG_MAX || (n == 0 && errno != 0) || end[strspn(end, " \t\n")] != '\0') { fprintf(stderr, "%s: not an unsigned long\n", number); exit(1); } printf("%lu=", n); for (;;) { unsigned long divisor = smallest_divisor(n); printf("%lu", divisor); if (divisor == n) break; printf("*"); n /= divisor; } printf("\n"); } int main(int argc, char **argv) { if (argc == 1) { char line[81]; while (fgets(line, sizeof line, stdin)) factor(line); } else { int i; for (i = 1; i < argc; ++i) factor(argv[i]); } return 0; }