factor.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. #include <u.h>
  10. #include <libc.h>
  11. #include <bio.h>
  12. #define whsiz (sizeof(wheel)/sizeof(wheel[0]))
  13. double wheel[] =
  14. {
  15. 2,10, 2, 4, 2, 4, 6, 2, 6, 4,
  16. 2, 4, 6, 6, 2, 6, 4, 2, 6, 4,
  17. 6, 8, 4, 2, 4, 2, 4, 8, 6, 4,
  18. 6, 2, 4, 6, 2, 6, 6, 4, 2, 4,
  19. 6, 2, 6, 4, 2, 4, 2,10,
  20. };
  21. Biobuf bin;
  22. void factor(double);
  23. void
  24. main(int argc, char *argv[])
  25. {
  26. double n;
  27. int i;
  28. char *l;
  29. if(argc > 1) {
  30. for(i=1; i<argc; i++) {
  31. n = atof(argv[i]);
  32. factor(n);
  33. }
  34. exits(0);
  35. }
  36. Binit(&bin, 0, OREAD);
  37. for(;;) {
  38. l = Brdline(&bin, '\n');
  39. if(l == 0)
  40. break;
  41. n = atof(l);
  42. if(n <= 0)
  43. break;
  44. factor(n);
  45. }
  46. exits(0);
  47. }
  48. void
  49. factor(double n)
  50. {
  51. double quot, d, s;
  52. int i;
  53. print("%.0f\n", n);
  54. if(n == 0)
  55. return;
  56. s = sqrt(n) + 1;
  57. while(modf(n/2, &quot) == 0) {
  58. print(" 2\n");
  59. n = quot;
  60. s = sqrt(n) + 1;
  61. }
  62. while(modf(n/3, &quot) == 0) {
  63. print(" 3\n");
  64. n = quot;
  65. s = sqrt(n) + 1;
  66. }
  67. while(modf(n/5, &quot) == 0) {
  68. print(" 5\n");
  69. n = quot;
  70. s = sqrt(n) + 1;
  71. }
  72. while(modf(n/7, &quot) == 0) {
  73. print(" 7\n");
  74. n = quot;
  75. s = sqrt(n) + 1;
  76. }
  77. d = 1;
  78. for(i=1;;) {
  79. d += wheel[i];
  80. while(modf(n/d, &quot) == 0) {
  81. print(" %.0f\n", d);
  82. n = quot;
  83. s = sqrt(n) + 1;
  84. }
  85. i++;
  86. if(i >= whsiz) {
  87. i = 0;
  88. if(d > s)
  89. break;
  90. }
  91. }
  92. if(n > 1)
  93. print(" %.0f\n",n);
  94. print("\n");
  95. }