Primes.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

main.c 1.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. #include "sieve.h"
  2. #include <stdio.h>
  3. #include <math.h>
  4. #include <stdlib.h>
  5. #include <signal.h>
  6. #include <unistd.h>
  7. #include <string.h>
  8. static void printfac(int64_t num, int64_t *buf)
  9. {
  10. int64_t n;
  11. int i = 0;
  12. fprintf(stdout, "%ld = ", num);
  13. while ((n = buf[i++]) != 0)
  14. {
  15. if (i == 1)
  16. fprintf(stdout, "%ld", n);
  17. else
  18. fprintf(stdout, " * %ld", n);
  19. }
  20. fprintf(stdout, "\n");
  21. }
  22. static sieve s;
  23. void onTerm(int signal)
  24. {
  25. sieve_free(&s);
  26. exit(1);
  27. }
  28. int main(int argc, char **argv)
  29. {
  30. if (argc != 2)
  31. {
  32. printf("Usage: %s <max-num>\n", argv[0]);
  33. exit(1);
  34. }
  35. int64_t maxnum = atol(argv[1]);
  36. sieve_init(&s, sqrt(maxnum) + 1);
  37. // Attach signal handler
  38. struct sigaction sa;
  39. memset(&sa, 0, sizeof(sa));
  40. sa.sa_handler = onTerm;
  41. sigaction(SIGTERM, &sa, NULL);
  42. sigaction(SIGINT, &sa, NULL);
  43. // Generate sieve
  44. fprintf(stderr, "Generating sieve...\n");
  45. sieve_generate(&s);
  46. fprintf(stderr, "done\n");
  47. fflush(stderr);
  48. int64_t buf[1024];
  49. // Main loop
  50. char line[1024];
  51. while (1)
  52. {
  53. // Read line
  54. int i = 0;
  55. int c;
  56. while ((c = getchar()) != EOF)
  57. {
  58. if (c == '\n')
  59. break;
  60. if (i < sizeof(buf) - 3)
  61. line[i++] = c;
  62. }
  63. line[i++] = 0;
  64. int64_t num = atol(line);
  65. if (num > maxnum)
  66. {
  67. printf("Number too big. Max size: %ld.\n", maxnum);
  68. }
  69. else if (num <= 0)
  70. {
  71. printf("Can only factor numbers >= 0.\n");
  72. }
  73. else
  74. {
  75. // Factor
  76. sieve_factor(&s, num, buf);
  77. // Print
  78. printfac(num, buf);
  79. }
  80. fflush(stdout);
  81. if (c == EOF)
  82. return 0;
  83. }
  84. sieve_free(&s);
  85. return 0;
  86. }