2 * Copyright (C) 2017 Denys Vlasenko <vda.linux@googlemail.com>
4 * Licensed under GPLv2, see file LICENSE in this source tree.
7 //config: bool "factor"
10 //config: factor factorizes integers
12 //applet:IF_FACTOR(APPLET(factor, BB_DIR_USR_BIN, BB_SUID_DROP))
14 //kbuild:lib-$(CONFIG_FACTOR) += factor.o
16 //usage:#define factor_trivial_usage
18 //usage:#define factor_full_usage "\n\n"
19 //usage: "Print prime factors"
24 # define dbg(...) bb_error_msg(__VA_ARGS__)
26 # define dbg(...) ((void)0)
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))
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
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
44 #error Cant find an integer type which is half as wide as ullong
47 /* Returns such x that x+1 > sqrt(N) */
48 static inline half_t isqrt(wide_t N)
53 // Never called with N < 1
57 /* First approximation of x+1 > sqrt(N) - all-ones, half as many bits:
58 * 1xxxxx -> 111 (six bits to three)
61 * 0001xx -> 011 and so on.
64 mask_2bits = TOPMOST_WIDE_BIT | (TOPMOST_WIDE_BIT >> 1);
65 while (!(N & mask_2bits)) {
69 dbg("x:%"HALF_FMT"x", x);
72 half_t y = (x + N/x) / 2;
73 dbg("y:%x y^2:%llx", y, (wide_t)y * y);
75 * "real" y may be one bit wider: 0x100000000 and get truncated to 0.
76 * In this case, "real" y is > x. The first check below is for this case:
78 if (y == 0 || y >= x) {
79 dbg("isqrt(%llx)=%"HALF_FMT"x", N, x);
86 static NOINLINE half_t isqrt_odd(wide_t N)
89 if (s && !(s & 1)) /* even? */
94 static NOINLINE void factorize(wide_t N)
110 max_factor = isqrt_odd(N);
116 /* The division is the most costly part of the loop.
117 * On 64bit CPUs, takes at best 12 cycles, often ~20.
119 while ((N % factor) == 0) { /* not likely */
121 printf(" %"HALF_FMT"u", factor);
122 max_factor = isqrt_odd(N);
125 if (factor >= max_factor)
128 /* Rudimentary wheel sieving: skip multiples of 3, 5 and 7:
129 * Every third odd number is divisible by three and thus isn't a prime:
130 * 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47...
131 * ^ ^ ^ ^ ^ ^ ^ _ ^ ^ _ ^ ^ ^ ^
132 * (^ = primes, _ = would-be-primes-if-not-divisible-by-5)
137 if (count3 && count5 && count7)
153 int factor_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
154 int factor_main(int argc UNUSED_PARAM, char **argv)
156 //// coreutils has undocumented option ---debug (three dashes)
157 //getopt32(argv, "");
162 //TODO: read from stdin
169 /* Coreutils compat */
170 numstr = skip_whitespace(*argv);
174 N = bb_strtoull(numstr, NULL, 10);