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