factor.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #include <u.h>
  2. #include <libc.h>
  3. #include <bio.h>
  4. #define whsiz (sizeof(wheel)/sizeof(wheel[0]))
  5. double wheel[] =
  6. {
  7. 2,10, 2, 4, 2, 4, 6, 2, 6, 4,
  8. 2, 4, 6, 6, 2, 6, 4, 2, 6, 4,
  9. 6, 8, 4, 2, 4, 2, 4, 8, 6, 4,
  10. 6, 2, 4, 6, 2, 6, 6, 4, 2, 4,
  11. 6, 2, 6, 4, 2, 4, 2,10,
  12. };
  13. Biobuf bin;
  14. void factor(double);
  15. void
  16. main(int argc, char *argv[])
  17. {
  18. double n;
  19. int i;
  20. char *l;
  21. if(argc > 1) {
  22. for(i=1; i<argc; i++) {
  23. n = atof(argv[i]);
  24. factor(n);
  25. }
  26. exits(0);
  27. }
  28. Binit(&bin, 0, OREAD);
  29. for(;;) {
  30. l = Brdline(&bin, '\n');
  31. if(l == 0)
  32. break;
  33. n = atof(l);
  34. if(n <= 0)
  35. break;
  36. factor(n);
  37. }
  38. exits(0);
  39. }
  40. void
  41. factor(double n)
  42. {
  43. double quot, d, s;
  44. int i;
  45. print("%.0f\n", n);
  46. if(n == 0)
  47. return;
  48. s = sqrt(n) + 1;
  49. while(modf(n/2, &quot) == 0) {
  50. print(" 2\n");
  51. n = quot;
  52. s = sqrt(n) + 1;
  53. }
  54. while(modf(n/3, &quot) == 0) {
  55. print(" 3\n");
  56. n = quot;
  57. s = sqrt(n) + 1;
  58. }
  59. while(modf(n/5, &quot) == 0) {
  60. print(" 5\n");
  61. n = quot;
  62. s = sqrt(n) + 1;
  63. }
  64. while(modf(n/7, &quot) == 0) {
  65. print(" 7\n");
  66. n = quot;
  67. s = sqrt(n) + 1;
  68. }
  69. d = 1;
  70. for(i=1;;) {
  71. d += wheel[i];
  72. while(modf(n/d, &quot) == 0) {
  73. print(" %.0f\n", d);
  74. n = quot;
  75. s = sqrt(n) + 1;
  76. }
  77. i++;
  78. if(i >= whsiz) {
  79. i = 0;
  80. if(d > s)
  81. break;
  82. }
  83. }
  84. if(n > 1)
  85. print(" %.0f\n",n);
  86. print("\n");
  87. }