xref: /netbsd-src/games/factor/factor.c (revision bbde328be4e75ea9ad02e9715ea13ca54b797ada)
1 /*	$NetBSD: factor.c,v 1.22 2010/04/28 18:04:31 drochner 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.22 2010/04/28 18:04:31 drochner 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 #if 0 /* debugging: limit table use to stress the "pollard" code */
102 #define pr_limit &prime[0]
103 #endif
104 
105 #define	PRIME_CHECKS	5
106 
107 #ifdef HAVE_OPENSSL
108 static BN_CTX *ctx;			/* just use a global context */
109 #endif
110 
111 static void pr_fact(BIGNUM *);		/* print factors of a value */
112 static void BN_print_dec_fp(FILE *, const BIGNUM *);
113 static void usage(void) __dead;
114 #ifdef HAVE_OPENSSL
115 static void pollard_rho(BIGNUM *);	/* print factors for big numbers */
116 #else
117 static char *BN_bn2dec(const BIGNUM *);
118 static BN_ULONG BN_div_word(BIGNUM *, BN_ULONG);
119 #endif
120 
121 
122 #ifndef HAVE_OPENSSL
123 static int
124 BN_dec2bn(BIGNUM **a, const char *str)
125 {
126 	char *p;
127 
128 	errno = 0;
129 	**a = strtoul(str, &p, 10);
130 	if (errno)
131 		err(1, "%s", str);
132 	return (*p == '\n' || *p == '\0');
133 }
134 #endif
135 
136 int
137 main(int argc, char *argv[])
138 {
139 	BIGNUM *val;
140 	int ch;
141 	char *p, buf[LINE_MAX];		/* > max number of digits. */
142 
143 #ifdef HAVE_OPENSSL
144 	ctx = BN_CTX_new();
145 #endif
146 	val = BN_new();
147 	if (val == NULL)
148 		errx(1, "can't initialise bignum");
149 
150 	while ((ch = getopt(argc, argv, "")) != -1)
151 		switch (ch) {
152 		case '?':
153 		default:
154 			usage();
155 		}
156 	argc -= optind;
157 	argv += optind;
158 
159 	/* No args supplied, read numbers from stdin. */
160 	if (argc == 0)
161 		for (;;) {
162 			if (fgets(buf, sizeof(buf), stdin) == NULL) {
163 				if (ferror(stdin))
164 					err(1, "stdin");
165 				exit (0);
166 			}
167 			for (p = buf; isblank(*p); ++p);
168 			if (*p == '\n' || *p == '\0')
169 				continue;
170 			if (*p == '-')
171 				errx(1, "negative numbers aren't permitted.");
172 			if (BN_dec2bn(&val, buf) == 0)
173 				errx(1, "%s: illegal numeric format.", argv[0]);
174 			pr_fact(val);
175 		}
176 	/* Factor the arguments. */
177 	else
178 		for (; *argv != NULL; ++argv) {
179 			if (argv[0][0] == '-')
180 				errx(1, "negative numbers aren't permitted.");
181 			if (BN_dec2bn(&val, argv[0]) == 0)
182 				errx(1, "%s: illegal numeric format.", argv[0]);
183 			pr_fact(val);
184 		}
185 	exit(0);
186 }
187 
188 /*
189  * pr_fact - print the factors of a number
190  *
191  * If the number is 0 or 1, then print the number and return.
192  * If the number is < 0, print -1, negate the number and continue
193  * processing.
194  *
195  * Print the factors of the number, from the lowest to the highest.
196  * A factor will be printed numtiple times if it divides the value
197  * multiple times.
198  *
199  * Factors are printed with leading tabs.
200  */
201 static void
202 pr_fact(BIGNUM *val)
203 {
204 	const ubig *fact;		/* The factor found. */
205 
206 	/* Firewall - catch 0 and 1. */
207 	if (BN_is_zero(val))	/* Historical practice; 0 just exits. */
208 		exit(0);
209 	if (BN_is_one(val)) {
210 		printf("1: 1\n");
211 		return;
212 	}
213 
214 	/* Factor value. */
215 
216 	BN_print_dec_fp(stdout, val);
217 	putchar(':');
218 	for (fact = &prime[0]; !BN_is_one(val); ++fact) {
219 		/* Look for the smallest factor. */
220 		while (fact <= pr_limit) {
221 			if (BN_mod_word(val, (BN_ULONG)*fact) == 0)
222 				break;
223 			fact++;
224 		}
225 
226 		/* Watch for primes larger than the table. */
227 		if (fact > pr_limit) {
228 #ifdef HAVE_OPENSSL
229 			BIGNUM *bnfact;
230 
231 			bnfact = BN_new();
232 			BN_set_word(bnfact, (BN_ULONG)*(fact - 1));
233 			BN_sqr(bnfact, bnfact, ctx);
234 			if (BN_cmp(bnfact, val) > 0
235 			    || BN_is_prime(val, PRIME_CHECKS, NULL, NULL,
236 					   NULL) == 1) {
237 				putchar(' ');
238 				BN_print_dec_fp(stdout, val);
239 			} else
240 				pollard_rho(val);
241 #else
242 			printf(" %s", BN_bn2dec(val));
243 #endif
244 			break;
245 		}
246 
247 		/* Divide factor out until none are left. */
248 		do {
249 			printf(" %lu", *fact);
250 			BN_div_word(val, (BN_ULONG)*fact);
251 		} while (BN_mod_word(val, (BN_ULONG)*fact) == 0);
252 
253 		/* Let the user know we're doing something. */
254 		fflush(stdout);
255 	}
256 	putchar('\n');
257 }
258 
259 /*
260  * Sigh..  No _decimal_ output to file functions in BN.
261  */
262 static void
263 BN_print_dec_fp(FILE *fp, const BIGNUM *num)
264 {
265 	char *buf;
266 
267 	buf = BN_bn2dec(num);
268 	if (buf == NULL)
269 		return;	/* XXX do anything here? */
270 	fprintf(fp, buf);
271 	free(buf);
272 }
273 
274 void
275 usage(void)
276 {
277 	fprintf(stderr, "usage: factor [value ...]\n");
278 	exit (0);
279 }
280 
281 
282 
283 
284 #ifdef HAVE_OPENSSL
285 static void
286 pollard_rho(BIGNUM *val)
287 {
288 	BIGNUM *x, *y, *tmp, *num;
289 	BN_ULONG a;
290 	unsigned int steps_taken, steps_limit;
291 
292 	x = BN_new();
293 	y = BN_new();
294 	tmp = BN_new();
295 	num = BN_new();
296 	a = 1;
297 restart:
298 	steps_taken = 0;
299 	steps_limit = 2;
300 	BN_set_word(x, 1);
301 	BN_copy(y, x);
302 
303 	for (;;) {
304 		BN_sqr(tmp, x, ctx);
305 		BN_add_word(tmp, a);
306 		BN_mod(x, tmp, val, ctx);
307 		BN_sub(tmp, x, y);
308 		if (BN_is_zero(tmp)) {
309 #ifdef DEBUG
310 			printf(" (loop)");
311 #endif
312 			a++;
313 			goto restart;
314 		}
315 		BN_gcd(tmp, tmp, val, ctx);
316 
317 		if (!BN_is_one(tmp)) {
318 			if (BN_is_prime(tmp, PRIME_CHECKS, NULL, NULL,
319 			    NULL) == 1) {
320 				putchar(' ');
321 				BN_print_dec_fp(stdout, tmp);
322 			} else {
323 #ifdef DEBUG
324 				printf(" (recurse for ");
325 				BN_print_dec_fp(stdout, tmp);
326 				putchar(')');
327 #endif
328 				pollard_rho(BN_dup(tmp));
329 #ifdef DEBUG
330 				printf(" (back)");
331 #endif
332 			}
333 			fflush(stdout);
334 
335 			BN_div(num, NULL, val, tmp, ctx);
336 			if (BN_is_one(num))
337 				return;
338 			if (BN_is_prime(num, PRIME_CHECKS, NULL, NULL,
339 			    NULL) == 1) {
340 				putchar(' ');
341 				BN_print_dec_fp(stdout, num);
342 				fflush(stdout);
343 				return;
344 			}
345 			BN_copy(val, num);
346 			goto restart;
347 		}
348 		steps_taken++;
349 		if (steps_taken == steps_limit) {
350 			BN_copy(y, x); /* teleport the turtle */
351 			steps_taken = 0;
352 			steps_limit *= 2;
353 			if (steps_limit == 0) {
354 #ifdef DEBUG
355 				printf(" (overflow)");
356 #endif
357 				a++;
358 				goto restart;
359 			}
360 		}
361 	}
362 }
363 #else
364 char *
365 BN_bn2dec(const BIGNUM *val)
366 {
367 	char *buf;
368 
369 	buf = malloc(100);
370 	if (!buf)
371 		return buf;
372 	snprintf(buf, 100, "%ld", (long)*val);
373 	return buf;
374 }
375 
376 static BN_ULONG
377 BN_div_word(BIGNUM *a, BN_ULONG b)
378 {
379 	BN_ULONG mod;
380 
381 	mod = *a % b;
382 	*a /= b;
383 	return mod;
384 }
385 #endif
386