w: new applet, alias to "who -H"
[oweals/busybox.git] / coreutils / factor.c
1 /*
2  * Copyright (C) 2017 Denys Vlasenko <vda.linux@googlemail.com>
3  *
4  * Licensed under GPLv2, see file LICENSE in this source tree.
5  */
6 //config:config FACTOR
7 //config:       bool "factor"
8 //config:       default y
9 //config:       help
10 //config:         factor factorizes integers
11
12 //applet:IF_FACTOR(APPLET(factor, BB_DIR_USR_BIN, BB_SUID_DROP))
13
14 //kbuild:lib-$(CONFIG_FACTOR) += factor.o
15
16 //usage:#define factor_trivial_usage
17 //usage:       "NUMBER..."
18 //usage:#define factor_full_usage "\n\n"
19 //usage:       "Print prime factors"
20
21 #include "libbb.h"
22
23 #if 0
24 # define dbg(...) bb_error_msg(__VA_ARGS__)
25 #else
26 # define dbg(...) ((void)0)
27 #endif
28
29 typedef unsigned long long wide_t;
30
31 #if ULLONG_MAX == (UINT_MAX * UINT_MAX + 2 * UINT_MAX)
32 /* "unsigned" is half as wide as ullong */
33 typedef unsigned half_t;
34 #define HALF_MAX UINT_MAX
35 #define HALF_FMT ""
36 #elif ULLONG_MAX == (ULONG_MAX * ULONG_MAX + 2 * ULONG_MAX)
37 /* long is half as wide as ullong */
38 typedef unsigned long half_t;
39 #define HALF_MAX ULONG_MAX
40 #define HALF_FMT "l"
41 #else
42 #error Cant find an integer type which is half as wide as ullong
43 #endif
44
45 static half_t isqrt_odd(wide_t N)
46 {
47         half_t s = isqrt(N);
48         /* Subtract 1 from even s, odd s won't change: */
49         /* (doesnt work for zero, but we know that s != 0 here) */
50         s = (s - 1) | 1;
51         return s;
52 }
53
54 static NOINLINE void factorize(wide_t N)
55 {
56         half_t factor;
57         half_t max_factor;
58         // unsigned count3;
59         // unsigned count5;
60         // unsigned count7;
61         // ^^^^^^^^^^^^^^^ commented-out simple siving code (easier to grasp).
62         // Faster sieving, using one word for potentially up to 6 counters:
63         // count upwards in each mask, counter "triggers" when it sets its mask to "100[0]..."
64         // 10987654321098765432109876543210 - bits 31-0 in 32-bit word
65         //    17777713333311111777775555333 - bit masks for counters for primes 3,5,7,11,13,17
66         //         100000100001000010001001 - value for adding 1 to each mask
67         //    10000010000010000100001000100 - value for checking that any mask reached msb
68         enum {
69                 SHIFT_3 = 1 << 0,
70                 SHIFT_5 = 1 << 3,
71                 SHIFT_7 = 1 << 7,
72                 INCREMENT_EACH = SHIFT_3 | SHIFT_5 | SHIFT_7,
73                 MULTIPLE_OF_3 = 1 << 2,
74                 MULTIPLE_OF_5 = 1 << 6,
75                 MULTIPLE_OF_7 = 1 << 11,
76                 MULTIPLE_3_5_7 = MULTIPLE_OF_3 | MULTIPLE_OF_5 | MULTIPLE_OF_7,
77         };
78         unsigned sieve_word;
79
80         if (N < 4)
81                 goto end;
82
83         while (!(N & 1)) {
84                 printf(" 2");
85                 N >>= 1;
86         }
87
88         /* The code needs to be optimized for the case where
89          * there are large prime factors. For example,
90          * this is not hard:
91          * 8262075252869367027 = 3 7 17 23 47 101 113 127 131 137 823
92          * (the largest factor to test is only ~sqrt(823) = 28)
93          * but this is:
94          * 18446744073709551601 = 53 348051774975651917
95          * the last factor requires testing up to
96          * 589959129 - about 100 million iterations.
97          */
98         max_factor = isqrt_odd(N);
99         // count3 = 3;
100         // count5 = 6;
101         // count7 = 9;
102         sieve_word = 0
103                 + (MULTIPLE_OF_3 - 3 * SHIFT_3)
104                 + (MULTIPLE_OF_5 - 6 * SHIFT_5)
105                 + (MULTIPLE_OF_7 - 9 * SHIFT_7)
106         ;
107         factor = 3;
108         for (;;) {
109                 /* The division is the most costly part of the loop.
110                  * On 64bit CPUs, takes at best 12 cycles, often ~20.
111                  */
112                 while ((N % factor) == 0) { /* not likely */
113                         N = N / factor;
114                         printf(" %"HALF_FMT"u", factor);
115                         max_factor = isqrt_odd(N);
116                 }
117  next_factor:
118                 if (factor >= max_factor)
119                         break;
120                 factor += 2;
121                 /* Rudimentary wheel sieving: skip multiples of 3, 5 and 7:
122                  * Every third odd number is divisible by three and thus isn't a prime:
123                  * 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47...
124                  * ^ ^   ^  ^     ^  ^     ^  _     ^  ^     _  ^     ^  ^     ^
125                  * (^ = primes, _ = would-be-primes-if-not-divisible-by-5)
126                  * The numbers with space under them are excluded by sieve 3.
127                  */
128                 // count7--;
129                 // count5--;
130                 // count3--;
131                 // if (count3 && count5 && count7)
132                 //      continue;
133                 sieve_word += INCREMENT_EACH;
134                 if (!(sieve_word & MULTIPLE_3_5_7))
135                         continue;
136                 /*
137                  * "factor" is multiple of 3 33% of the time (count3 reached 0),
138                  * else, multiple of 5 13% of the time,
139                  * else, multiple of 7 7.6% of the time.
140                  * Cumulatively, with 3,5,7 sieving we are here 54.3% of the time.
141                  */
142                 // if (count3 == 0)
143                 //      count3 = 3;
144                 if (sieve_word & MULTIPLE_OF_3)
145                         sieve_word -= SHIFT_3 * 3;
146                 // if (count5 == 0)
147                 //      count5 = 5;
148                 if (sieve_word & MULTIPLE_OF_5)
149                         sieve_word -= SHIFT_5 * 5;
150                 // if (count7 == 0)
151                 //      count7 = 7;
152                 if (sieve_word & MULTIPLE_OF_7)
153                         sieve_word -= SHIFT_7 * 7;
154                 goto next_factor;
155         }
156  end:
157         if (N > 1)
158                 printf(" %llu", N);
159         bb_putchar('\n');
160 }
161
162 int factor_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
163 int factor_main(int argc UNUSED_PARAM, char **argv)
164 {
165         //// coreutils has undocumented option ---debug (three dashes)
166         //getopt32(argv, "");
167         //argv += optind;
168         argv++;
169
170         if (!*argv)
171                 //TODO: read from stdin
172                 bb_show_usage();
173
174         do {
175                 wide_t N;
176                 const char *numstr;
177
178                 /* Coreutils compat */
179                 numstr = skip_whitespace(*argv);
180                 if (*numstr == '+')
181                         numstr++;
182
183                 N = bb_strtoull(numstr, NULL, 10);
184                 if (errno)
185                         bb_show_usage();
186                 printf("%llu:", N);
187                 factorize(N);
188         } while (*++argv);
189
190         return EXIT_SUCCESS;
191 }