123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- #include "sieve.h"
-
- #include <stdio.h>
- #include <math.h>
- #include <stdlib.h>
- #include <signal.h>
- #include <unistd.h>
- #include <string.h>
-
- static void printfac(int64_t num, int64_t *buf)
- {
- int64_t n;
- int i = 0;
- fprintf(stdout, "%ld = ", num);
- while ((n = buf[i++]) != 0)
- {
- if (i == 1)
- fprintf(stdout, "%ld", n);
- else
- fprintf(stdout, " * %ld", n);
- }
- fprintf(stdout, "\n");
- }
-
- static sieve s;
-
- void onTerm(int signal)
- {
- sieve_free(&s);
- exit(1);
- }
-
- int main(int argc, char **argv)
- {
- if (argc != 2)
- {
- printf("Usage: %s <max-num>\n", argv[0]);
- exit(1);
- }
-
- int64_t maxnum = atol(argv[1]);
-
- sieve_init(&s, sqrt(maxnum) + 1);
-
- // Attach signal handler
- struct sigaction sa;
- memset(&sa, 0, sizeof(sa));
- sa.sa_handler = onTerm;
- sigaction(SIGTERM, &sa, NULL);
- sigaction(SIGINT, &sa, NULL);
-
- // Generate sieve
- fprintf(stderr, "Generating sieve...\n");
- sieve_generate(&s);
- fprintf(stderr, "done\n");
- fflush(stderr);
-
- int64_t buf[1024];
-
- // Main loop
- char line[1024];
- while (1)
- {
- // Read line
- int i = 0;
- int c;
- while ((c = getchar()) != EOF)
- {
- if (c == '\n')
- break;
-
- if (i < sizeof(buf) - 3)
- line[i++] = c;
- }
- line[i++] = 0;
-
- int64_t num = atol(line);
- if (num > maxnum)
- {
- printf("Number too big. Max size: %ld.\n", maxnum);
- }
- else if (num <= 0)
- {
- printf("Can only factor numbers >= 0.\n");
- }
- else
- {
- // Factor
- sieve_factor(&s, num, buf);
-
- // Print
- printfac(num, buf);
- }
-
- fflush(stdout);
-
- if (c == EOF)
- return 0;
- }
-
- sieve_free(&s);
-
- return 0;
- }
|