factor.c revision 1.9
1/*	$OpenBSD: factor.c,v 1.9 2001/08/19 17:12:40 pjanzen 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. All advertising materials mentioning features or use of this software
20 *    must display the following acknowledgement:
21 *	This product includes software developed by the University of
22 *	California, Berkeley and its contributors.
23 * 4. Neither the name of the University nor the names of its contributors
24 *    may be used to endorse or promote products derived from this software
25 *    without specific prior written permission.
26 *
27 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 * SUCH DAMAGE.
38 */
39
40#ifndef lint
41static char copyright[] =
42"@(#) Copyright (c) 1989, 1993\n\
43	The Regents of the University of California.  All rights reserved.\n";
44#endif /* not lint */
45
46#ifndef lint
47#if 0
48static char sccsid[] = "@(#)factor.c	8.4 (Berkeley) 5/4/95";
49#else
50static char rcsid[] = "$OpenBSD: factor.c,v 1.9 2001/08/19 17:12:40 pjanzen Exp $";
51#endif
52#endif /* not lint */
53
54/*
55 * factor - factor a number into primes
56 *
57 * By: Landon Curt Noll   chongo@toad.com,   ...!{sun,tolsoft}!hoptoad!chongo
58 *
59 *   chongo <for a good prime call: 391581 * 2^216193 - 1> /\oo/\
60 *
61 * usage:
62 *	factor [number] ...
63 *
64 * The form of the output is:
65 *
66 *	number: factor1 factor1 factor2 factor3 factor3 factor3 ...
67 *
68 * where factor1 < factor2 < factor3 < ...
69 *
70 * If no args are given, the list of numbers are read from stdin.
71 */
72
73#include <sys/types.h>
74#include <err.h>
75#include <ctype.h>
76#include <errno.h>
77#include <limits.h>
78#include <stdio.h>
79#include <stdlib.h>
80#include <unistd.h>
81
82#include "primes.h"
83
84/*
85 * prime[i] is the (i+1)th prime.
86 *
87 * We are able to sieve 2^32-1 because this byte table yields all primes
88 * up to 65537 and 65537^2 > 2^32-1.
89 */
90extern const ubig prime[];
91extern const ubig *pr_limit;		/* largest prime in the prime array */
92
93void	pr_fact __P((ubig));	/* print factors of a value */
94void	usage __P((void));
95
96int
97main(argc, argv)
98	int argc;
99	char *argv[];
100{
101	ubig val;
102	int ch;
103	char *p, buf[100];		/* > max number of digits. */
104
105	/* revoke privs */
106	setegid(getgid());
107	setgid(getgid());
108
109	while ((ch = getopt(argc, argv, "")) != -1)
110		switch (ch) {
111		case '?':
112		default:
113			usage();
114		}
115	argc -= optind;
116	argv += optind;
117
118	/* No args supplied, read numbers from stdin. */
119	if (argc == 0)
120		for (;;) {
121			if (fgets(buf, sizeof(buf), stdin) == NULL) {
122				if (ferror(stdin))
123					err(1, "stdin");
124				exit (0);
125			}
126			if (*(p = buf + strlen(buf) - 1) == '\n')
127				*p = '\0';
128			for (p = buf; isblank(*p); ++p);
129			if (*p == '\0')
130				continue;
131			if (*p == '-')
132				errx(1, "negative numbers aren't permitted.");
133			errno = 0;
134			val = strtoul(buf, &p, 10);
135			if (errno)
136				err(1, "%s", buf);
137			for (; isblank(*p); ++p);
138			if (*p != '\0')
139				errx(1, "%s: illegal numeric format.", buf);
140			pr_fact(val);
141		}
142	/* Factor the arguments. */
143	else
144		for (; *argv != NULL; ++argv) {
145			if (argv[0][0] == '-')
146				errx(1, "negative numbers aren't permitted.");
147			errno = 0;
148			val = strtoul(argv[0], &p, 10);
149			if (errno)
150				err(1, "%s", argv[0]);
151			if (*p != '\0')
152				errx(1, "%s: illegal numeric format.", argv[0]);
153			pr_fact(val);
154		}
155	exit(0);
156}
157
158/*
159 * pr_fact - print the factors of a number
160 *
161 * If the number is 0 or 1, then print the number and return.
162 * If the number is < 0, print -1, negate the number and continue
163 * processing.
164 *
165 * Print the factors of the number, from the lowest to the highest.
166 * A factor will be printed numtiple times if it divides the value
167 * multiple times.
168 *
169 * Factors are printed with leading tabs.
170 */
171void
172pr_fact(val)
173	ubig val;		/* Factor this value. */
174{
175	const ubig *fact;	/* The factor found. */
176
177	/* Firewall - catch 0 and 1. */
178	if (val == 0)		/* Historical practice; 0 just exits. */
179		exit(0);
180	if (val == 1) {
181		(void)printf("1: 1\n");
182		return;
183	}
184
185	/* Factor value. */
186	(void)printf("%lu:", (unsigned long) val);
187	for (fact = &prime[0]; val > 1; ++fact) {
188		/* Look for the smallest factor. */
189		do {
190			if (val % (long)*fact == 0)
191				break;
192		} while (++fact <= pr_limit);
193
194		/* Watch for primes larger than the table. */
195		if (fact > pr_limit) {
196			(void)printf(" %lu", (unsigned long) val);
197			break;
198		}
199
200		/* Divide factor out until none are left. */
201		do {
202			(void)printf(" %lu", (unsigned long) *fact);
203			val /= (long)*fact;
204		} while ((val % (long)*fact) == 0);
205
206		/* Let the user know we're doing something. */
207		(void)fflush(stdout);
208	}
209	(void)putchar('\n');
210}
211
212void
213usage()
214{
215	(void)fprintf(stderr, "usage: factor [value ...]\n");
216	exit (0);
217}
218