xref: /netbsd-src/games/factor/factor.c (revision 3816d47b2c42fcd6e549e3407f842a5b1a1d23ad)
1 /*	$NetBSD: factor.c,v 1.19 2009/08/12 05:54:31 dholland Exp $	*/
2 
3 /*
4  * Copyright (c) 1989, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Landon Curt Noll.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #include <sys/cdefs.h>
36 #ifndef lint
37 __COPYRIGHT("@(#) Copyright (c) 1989, 1993\
38  The Regents of the University of California.  All rights reserved.");
39 #endif /* not lint */
40 
41 #ifndef lint
42 #if 0
43 static char sccsid[] = "@(#)factor.c	8.4 (Berkeley) 5/4/95";
44 #else
45 __RCSID("$NetBSD: factor.c,v 1.19 2009/08/12 05:54:31 dholland Exp $");
46 #endif
47 #endif /* not lint */
48 
49 /*
50  * factor - factor a number into primes
51  *
52  * By: Landon Curt Noll   chongo@toad.com,   ...!{sun,tolsoft}!hoptoad!chongo
53  *
54  *   chongo <for a good prime call: 391581 * 2^216193 - 1> /\oo/\
55  *
56  * usage:
57  *	factor [number] ...
58  *
59  * The form of the output is:
60  *
61  *	number: factor1 factor1 factor2 factor3 factor3 factor3 ...
62  *
63  * where factor1 <= factor2 <= factor3 <= ...
64  *
65  * If no args are given, the list of numbers are read from stdin.
66  */
67 
68 #include <ctype.h>
69 #include <err.h>
70 #include <errno.h>
71 #include <limits.h>
72 #include <stdio.h>
73 #include <stdlib.h>
74 #include <unistd.h>
75 
76 #ifdef HAVE_OPENSSL
77 #include <openssl/bn.h>
78 #else
79 typedef long	BIGNUM;
80 typedef u_long	BN_ULONG;
81 static int BN_dec2bn(BIGNUM **a, const char *str);
82 #define BN_new()		((BIGNUM *)calloc(sizeof(BIGNUM), 1))
83 #define BN_is_zero(v)		(*(v) == 0)
84 #define BN_is_one(v)		(*(v) == 1)
85 #define BN_new()		((BIGNUM *)calloc(sizeof(BIGNUM), 1))
86 #define BN_is_zero(v)		(*(v) == 0)
87 #define BN_is_one(v)		(*(v) == 1)
88 #define BN_mod_word(a, b)	(*(a) % (b))
89 #endif
90 
91 #include "primes.h"
92 
93 /*
94  * prime[i] is the (i-1)th prime.
95  *
96  * We are able to sieve 2^32-1 because this byte table yields all primes
97  * up to 65537 and 65537^2 > 2^32-1.
98  */
99 extern const ubig prime[];
100 extern const ubig *pr_limit;		/* largest prime in the prime array */
101 
102 #define	PRIME_CHECKS	5
103 
104 #ifdef HAVE_OPENSSL
105 static BN_CTX *ctx;			/* just use a global context */
106 #endif
107 
108 static void pr_fact(BIGNUM *);		/* print factors of a value */
109 static void BN_print_dec_fp(FILE *, const BIGNUM *);
110 static void usage(void) __dead;
111 #ifdef HAVE_OPENSSL
112 static void pollard_pminus1(BIGNUM *);	/* print factors for big numbers */
113 #else
114 static char *BN_bn2dec(const BIGNUM *);
115 static BN_ULONG BN_div_word(BIGNUM *, BN_ULONG);
116 #endif
117 
118 
119 #ifndef HAVE_OPENSSL
120 static int
121 BN_dec2bn(BIGNUM **a, const char *str)
122 {
123 	char *p;
124 
125 	errno = 0;
126 	**a = strtoul(str, &p, 10);
127 	if (errno)
128 		err(1, "%s", str);
129 	return (*p == '\n' || *p == '\0');
130 }
131 #endif
132 
133 int
134 main(int argc, char *argv[])
135 {
136 	BIGNUM *val;
137 	int ch;
138 	char *p, buf[LINE_MAX];		/* > max number of digits. */
139 
140 #ifdef HAVE_OPENSSL
141 	ctx = BN_CTX_new();
142 #endif
143 	val = BN_new();
144 	if (val == NULL)
145 		errx(1, "can't initialise bignum");
146 
147 	while ((ch = getopt(argc, argv, "")) != -1)
148 		switch (ch) {
149 		case '?':
150 		default:
151 			usage();
152 		}
153 	argc -= optind;
154 	argv += optind;
155 
156 	/* No args supplied, read numbers from stdin. */
157 	if (argc == 0)
158 		for (;;) {
159 			if (fgets(buf, sizeof(buf), stdin) == NULL) {
160 				if (ferror(stdin))
161 					err(1, "stdin");
162 				exit (0);
163 			}
164 			for (p = buf; isblank(*p); ++p);
165 			if (*p == '\n' || *p == '\0')
166 				continue;
167 			if (*p == '-')
168 				errx(1, "negative numbers aren't permitted.");
169 			if (BN_dec2bn(&val, buf) == 0)
170 				errx(1, "%s: illegal numeric format.", argv[0]);
171 			pr_fact(val);
172 		}
173 	/* Factor the arguments. */
174 	else
175 		for (; *argv != NULL; ++argv) {
176 			if (argv[0][0] == '-')
177 				errx(1, "negative numbers aren't permitted.");
178 			if (BN_dec2bn(&val, argv[0]) == 0)
179 				errx(1, "%s: illegal numeric format.", argv[0]);
180 			pr_fact(val);
181 		}
182 	exit(0);
183 }
184 
185 /*
186  * pr_fact - print the factors of a number
187  *
188  * If the number is 0 or 1, then print the number and return.
189  * If the number is < 0, print -1, negate the number and continue
190  * processing.
191  *
192  * Print the factors of the number, from the lowest to the highest.
193  * A factor will be printed numtiple times if it divides the value
194  * multiple times.
195  *
196  * Factors are printed with leading tabs.
197  */
198 static void
199 pr_fact(BIGNUM *val)
200 {
201 	const ubig *fact;		/* The factor found. */
202 
203 	/* Firewall - catch 0 and 1. */
204 	if (BN_is_zero(val))	/* Historical practice; 0 just exits. */
205 		exit(0);
206 	if (BN_is_one(val)) {
207 		printf("1: 1\n");
208 		return;
209 	}
210 
211 	/* Factor value. */
212 
213 	BN_print_dec_fp(stdout, val);
214 	putchar(':');
215 	for (fact = &prime[0]; !BN_is_one(val); ++fact) {
216 		/* Look for the smallest factor. */
217 		do {
218 			if (BN_mod_word(val, (BN_ULONG)*fact) == 0)
219 				break;
220 		} while (++fact <= pr_limit);
221 
222 		/* Watch for primes larger than the table. */
223 		if (fact > pr_limit) {
224 #ifdef HAVE_OPENSSL
225 			BIGNUM *bnfact;
226 
227 			bnfact = BN_new();
228 			BN_set_word(bnfact, *(fact - 1));
229 			BN_sqr(bnfact, bnfact, ctx);
230 			if (BN_cmp(bnfact, val) > 0
231 			    || BN_is_prime(val, PRIME_CHECKS, NULL, NULL,
232 					   NULL) == 1) {
233 				putchar(' ');
234 				BN_print_dec_fp(stdout, val);
235 			} else
236 				pollard_pminus1(val);
237 #else
238 			printf(" %s", BN_bn2dec(val));
239 #endif
240 			break;
241 		}
242 
243 		/* Divide factor out until none are left. */
244 		do {
245 			printf(" %lu", *fact);
246 			BN_div_word(val, (BN_ULONG)*fact);
247 		} while (BN_mod_word(val, (BN_ULONG)*fact) == 0);
248 
249 		/* Let the user know we're doing something. */
250 		fflush(stdout);
251 	}
252 	putchar('\n');
253 }
254 
255 /*
256  * Sigh..  No _decimal_ output to file functions in BN.
257  */
258 static void
259 BN_print_dec_fp(FILE *fp, const BIGNUM *num)
260 {
261 	char *buf;
262 
263 	buf = BN_bn2dec(num);
264 	if (buf == NULL)
265 		return;	/* XXX do anything here? */
266 	fprintf(fp, buf);
267 	free(buf);
268 }
269 
270 void
271 usage(void)
272 {
273 	fprintf(stderr, "usage: factor [value ...]\n");
274 	exit (0);
275 }
276 
277 
278 
279 
280 #ifdef HAVE_OPENSSL
281 /* pollard p-1, algorithm from Jim Gillogly, May 2000 */
282 
283 static void
284 pollard_pminus1(BIGNUM *val)
285 {
286 	BIGNUM *base, *rbase, *num, *i, *x;
287 
288 	base = BN_new();
289 	rbase = BN_new();
290 	num = BN_new();
291 	i = BN_new();
292 	x = BN_new();
293 
294 	BN_set_word(rbase, 1);
295  newbase:
296 	BN_add_word(rbase, 1);
297 	BN_set_word(i, 2);
298 	BN_copy(base, rbase);
299 
300 	for (;;) {
301 		BN_mod_exp(base, base, i, val, ctx);
302 		if (BN_is_one(base))
303 			goto newbase;
304 
305 		BN_copy(x, base);
306 		BN_sub_word(x, 1);
307 		BN_gcd(x, x, val, ctx);
308 
309 		if (!BN_is_one(x)) {
310 			if (BN_is_prime(x, PRIME_CHECKS, NULL, NULL,
311 			    NULL) == 1) {
312 				putchar(' ');
313 				BN_print_dec_fp(stdout, x);
314 			} else
315 				pollard_pminus1(x);
316 			fflush(stdout);
317 
318 			BN_div(num, NULL, val, x, ctx);
319 			if (BN_is_one(num))
320 				return;
321 			if (BN_is_prime(num, PRIME_CHECKS, NULL, NULL,
322 			    NULL) == 1) {
323 				putchar(' ');
324 				BN_print_dec_fp(stdout, num);
325 				fflush(stdout);
326 				return;
327 			}
328 			BN_copy(val, num);
329 		}
330 		BN_add_word(i, 1);
331 	}
332 }
333 #else
334 char *
335 BN_bn2dec(const BIGNUM *val)
336 {
337 	char *buf;
338 
339 	buf = malloc(100);
340 	if (!buf)
341 		return buf;
342 	snprintf(buf, 100, "%ld", (long)*val);
343 	return buf;
344 }
345 
346 static BN_ULONG
347 BN_div_word(BIGNUM *a, BN_ULONG b)
348 {
349 	BN_ULONG mod;
350 
351 	mod = *a % b;
352 	*a /= b;
353 	return mod;
354 }
355 #endif
356