fork download
  1. // Prime factors.
  2.  
  3. #include <stdlib.h>
  4. #include <stdio.h>
  5.  
  6. #define ARRAY_MAX_SIZE 100
  7. #define ARRAY_INITIALIZER ((struct array) {{}, 0})
  8.  
  9. struct array {
  10. int p[ARRAY_MAX_SIZE]; size_t n;
  11. };
  12.  
  13. void append(struct array *a, int i)
  14. {
  15. if (a->n < ARRAY_MAX_SIZE) {
  16. a->p[a->n++] = i;
  17. } else {
  18. fprintf(stderr, "overflow in %s", __func__);
  19. exit(EXIT_FAILURE);
  20. }
  21. }
  22.  
  23. void print(const struct array *a, int end)
  24. {
  25. putchar('[');
  26. for (size_t i = 0; i < a->n; i++)
  27. printf("%s%d", i ? ", " : "", a->p[i]);
  28. putchar(']');
  29. if (end != 0)
  30. putchar(end);
  31. }
  32.  
  33. void factor(int n, struct array *r)
  34. {
  35. for (int i = 2; i*i <= n; i++) {
  36. while (n%i == 0) {
  37. append(r, i);
  38. n = n/i;
  39. }
  40. }
  41. if (n > 1)
  42. append(r, n);
  43. }
  44.  
  45. int main(void)
  46. {
  47. struct array r = ARRAY_INITIALIZER;
  48. factor(2*3*5*7*11*13*17*19*23, &r);
  49. print(&r, '\n');
  50. r = ARRAY_INITIALIZER;
  51. factor(0x80000, &r);
  52. print(&r, '\n');
  53. r = ARRAY_INITIALIZER;
  54. factor(0x7FFFF, &r);
  55. print(&r, '\n');
  56. return 0;
  57. }
Success #stdin #stdout 0s 5284KB
stdin
Standard input is empty
stdout
[2, 3, 5, 7, 11, 13, 17, 19, 23]
[2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
[524287]