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