1 /* $OpenBSD: factor.c,v 1.30 2016/09/01 10:48:38 tb Exp $ */
2 /* $NetBSD: factor.c,v 1.5 1995/03/23 08:28:07 cgd Exp $ */
3
4 /*
5 * Copyright (c) 1989, 1993
6 * The Regents of the University of California. All rights reserved.
7 *
8 * This code is derived from software contributed to Berkeley by
9 * Landon Curt Noll.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. Neither the name of the University nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * SUCH DAMAGE.
34 */
35
36 /*
37 * factor - factor a number into primes
38 *
39 * By: Landon Curt Noll chongo@toad.com, ...!{sun,tolsoft}!hoptoad!chongo
40 *
41 * chongo <for a good prime call: 391581 * 2^216193 - 1> /\oo/\
42 *
43 * usage:
44 * factor [number ...]
45 *
46 * The form of the output is:
47 *
48 * number: factor1 factor1 factor2 factor3 factor3 factor3 ...
49 *
50 * where factor1 < factor2 < factor3 < ...
51 *
52 * If no args are given, the list of numbers are read from stdin.
53 */
54
55 #include <ctype.h>
56 #include <err.h>
57 #include <errno.h>
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <string.h>
61 #include <unistd.h>
62
63 #include "primes.h"
64
65 /*
66 * prime[i] is the (i+1)th prime.
67 *
68 * We are able to sieve 2^32-1 because this byte table yields all primes
69 * up to 65537 and 65537^2 > 2^32-1.
70 */
71 extern const ubig prime[];
72 extern const ubig *pr_limit; /* largest prime in the prime array */
73 extern const char pattern[];
74 extern const int pattern_size;
75
76 static void pr_fact(u_int64_t); /* print factors of a value */
77 static void pr_bigfact(u_int64_t);
78 static u_int64_t usqrt(u_int64_t);
79 static void __dead usage(void);
80
81 int
main(int argc,char * argv[])82 main(int argc, char *argv[])
83 {
84 u_int64_t val;
85 int ch;
86 char *p, buf[100]; /* > max number of digits. */
87
88 if (pledge("stdio", NULL) == -1)
89 err(1, "pledge");
90
91 while ((ch = getopt(argc, argv, "h")) != -1) {
92 switch (ch) {
93 case 'h':
94 default:
95 usage();
96 }
97 }
98 argc -= optind;
99 argv += optind;
100
101 /* No args supplied, read numbers from stdin. */
102 if (argc == 0) {
103 for (;;) {
104 if (fgets(buf, sizeof(buf), stdin) == NULL) {
105 if (ferror(stdin))
106 err(1, "stdin");
107 return 0;
108 }
109 buf[strcspn(buf, "\n")] = '\0';
110 for (p = buf; isblank((unsigned char)*p); ++p)
111 ;
112 if (*p == '\0')
113 continue;
114 if (*p == '-')
115 errx(1, "negative numbers aren't permitted.");
116 errno = 0;
117 val = strtoull(buf, &p, 10);
118 if (errno)
119 err(1, "%s", buf);
120 for (; isblank((unsigned char)*p); ++p)
121 ;
122 if (*p != '\0')
123 errx(1, "%s: illegal numeric format.", buf);
124 pr_fact(val);
125 }
126 /* Factor the arguments. */
127 } else {
128 for (; *argv != NULL; ++argv) {
129 if (argv[0][0] == '-')
130 errx(1, "negative numbers aren't permitted.");
131 errno = 0;
132 val = strtoull(argv[0], &p, 10);
133 if (errno)
134 err(1, "%s", argv[0]);
135 if (*p != '\0')
136 errx(1, "%s: illegal numeric format.", argv[0]);
137 pr_fact(val);
138 }
139 }
140 return 0;
141 }
142
143 /*
144 * pr_fact - print the prime factors of a number
145 *
146 * If the number is 0 or 1, then print the number and return.
147 * If the number is < 0, print -1, negate the number and continue
148 * processing.
149 *
150 * Print the factors of the number, from the lowest to the highest.
151 * A prime factor will be printed as often as it divides the value.
152 *
153 * Prime factors are printed with leading spaces.
154 */
155 static void
pr_fact(u_int64_t val)156 pr_fact(u_int64_t val) /* Factor this value. */
157 {
158 const ubig *fact; /* The factor found. */
159
160 /* Firewall - catch 0 and 1. */
161 if (val == 0) /* Historical practice; 0 just exits. */
162 exit(0);
163 if (val == 1) {
164 (void)printf("1: 1\n");
165 return;
166 }
167
168 /* Factor value. */
169 (void)printf("%llu:", val);
170 fflush(stdout);
171 for (fact = &prime[0]; val > 1; ++fact) {
172 /* Look for the smallest factor. */
173 do {
174 if (val % (long)*fact == 0)
175 break;
176 } while (++fact <= pr_limit);
177
178 /* Watch for primes larger than the table. */
179 if (fact > pr_limit) {
180 if (val > BIG)
181 pr_bigfact(val);
182 else
183 (void)printf(" %llu", val);
184 break;
185 }
186
187 /* Divide factor out until none are left. */
188 do {
189 (void)printf(" %lu", (unsigned long) *fact);
190 val /= (long)*fact;
191 } while ((val % (long)*fact) == 0);
192
193 /* Let the user know we're doing something. */
194 (void)fflush(stdout);
195 }
196 (void)putchar('\n');
197 }
198
199 /*
200 * At this point, our number may have factors greater than those in primes[];
201 * however, we can generate primes up to 32 bits (see primes(6)), which is
202 * sufficient to factor a 64-bit quad.
203 */
204 static void
pr_bigfact(u_int64_t val)205 pr_bigfact(u_int64_t val) /* Factor this value. */
206 {
207 u_int64_t start, stop;
208 ubig factor;
209 char *q;
210 const ubig *p;
211 ubig fact_lim, mod;
212 char *tab_lim;
213 char table[TABSIZE]; /* Eratosthenes sieve of odd numbers */
214
215 start = *pr_limit + 2;
216 stop = usqrt(val) + 1;
217 if ((stop & 0x1) == 0)
218 stop++;
219 /*
220 * Following code barely modified from that in primes(6)
221 *
222 * we shall sieve a bytemap window, note primes and move the window
223 * upward until we pass the stop point
224 */
225 while (start < stop) {
226 /*
227 * factor out 3, 5, 7, 11 and 13
228 */
229 /* initial pattern copy */
230 factor = (start%(2*3*5*7*11*13))/2; /* starting copy spot */
231 memcpy(table, &pattern[factor], pattern_size-factor);
232 /* main block pattern copies */
233 for (fact_lim = pattern_size - factor;
234 fact_lim + pattern_size <= TABSIZE;
235 fact_lim += pattern_size) {
236 memcpy(&table[fact_lim], pattern, pattern_size);
237 }
238 /* final block pattern copy */
239 memcpy(&table[fact_lim], pattern, TABSIZE-fact_lim);
240
241 if (stop-start > TABSIZE+TABSIZE) {
242 tab_lim = &table[TABSIZE]; /* sieve it all */
243 fact_lim = usqrt(start + TABSIZE + TABSIZE + 1);
244 } else {
245 tab_lim = &table[(stop - start)/2]; /* partial sieve */
246 fact_lim = usqrt(stop + 1);
247 }
248 /* sieve for factors >= 17 */
249 factor = 17; /* 17 is first prime to use */
250 p = &prime[7]; /* 19 is next prime, pi(19)=7 */
251 do {
252 /* determine the factor's initial sieve point */
253 mod = start % factor;
254 if (mod & 0x1)
255 q = &table[(factor-mod)/2];
256 else
257 q = &table[mod ? factor-(mod/2) : 0];
258 /* sieve for our current factor */
259 for ( ; q < tab_lim; q += factor) {
260 *q = '\0'; /* sieve out a spot */
261 }
262 } while ((factor=(ubig)(*(p++))) <= fact_lim);
263
264 /*
265 * use generated primes
266 */
267 for (q = table; q < tab_lim; ++q, start+=2) {
268 if (*q) {
269 if (val % start == 0) {
270 do {
271 printf(" %llu", start);
272 val /= start;
273 } while ((val % start) == 0);
274 (void)fflush(stdout);
275 stop = usqrt(val) + 1;
276 if ((stop & 0x1) == 0)
277 stop++;
278 }
279 }
280 }
281 }
282 if (val > 1)
283 printf(" %llu", val);
284 }
285
286 /* Code taken from ping.c */
287 static u_int64_t
usqrt(u_int64_t n)288 usqrt(u_int64_t n)
289 {
290 u_int64_t y, x = 1;
291
292 if (n == 0 || n == 1)
293 return n;
294
295 do { /* newton was a stinker */
296 y = x;
297 x = n / x;
298 x += y;
299 x /= 2;
300 } while (((y < x) && (x - y) > 1) || (y - x) > 1);
301
302 return x;
303 }
304
305 static void __dead
usage(void)306 usage(void)
307 {
308 (void)fprintf(stderr, "usage: %s [number ...]\n", getprogname());
309 exit (1);
310 }
311