1 /* factor -- print factors of n. lose if n > 2^32.
2 Copyright (C) 86, 1995 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
18 /* Written by Paul Rubin <phr@ocf.berkeley.edu>. */
22 #include <sys/types.h>
29 #include "long-options.h"
31 #include "readtokens.h"
33 /* Token delimiters when reading from a file. */
36 /* FIXME: if this program is ever modified to factor integers larger
37 than 2^128, this (and the algorithm :-) will have to change. */
38 #define MAX_N_FACTORS 128
40 /* The name this program was run with. */
48 fprintf (stderr, "Try `%s --help' for more information.\n",
56 program_name, program_name);
59 --help display this help and exit\n\
60 --version output version information and exit\n\
67 factor (n0, max_n_factors, factors)
70 unsigned long *factors;
72 register unsigned long n = n0, d;
80 assert (n_factors < max_n_factors);
81 factors[n_factors++] = 2;
85 /* The exit condition in the following loop is correct because
86 any time it is tested one of these 3 conditions holds:
89 (3) n is composite but has no factors less than d.
90 If (1) or (2) obviously the right thing happens.
91 If (3), then since n is composite it is >= d^2. */
92 for (d = 3; d * d <= n; d += 2)
96 assert (n_factors < max_n_factors);
97 factors[n_factors++] = d;
101 if (n != 1 || n0 == 1)
103 assert (n_factors < max_n_factors);
104 factors[n_factors++] = n;
114 unsigned long int factors[MAX_N_FACTORS];
118 n_factors = factor (n, MAX_N_FACTORS, factors);
119 for (i = 0; i < n_factors; i++)
120 printf (" %lu\n", factors[i]);
127 token_buffer tokenbuffer;
129 init_tokenbuffer (&tokenbuffer);
133 long int token_length;
135 token_length = readtoken (stdin, DELIM, sizeof (DELIM) - 1,
137 if (token_length < 0)
139 /* FIXME: Use xstrtoul, not atoi. */
140 print_factors ((unsigned long) atoi (tokenbuffer.buffer));
142 free (tokenbuffer.buffer);
150 program_name = argv[0];
152 parse_long_options (argc, argv, "factor", version_string, usage);
156 error (0, 0, "too many arguments");
164 print_factors ((unsigned long) atoi (argv[1]));
168 fprintf (stderr, "Usage: %s [number]\n", argv[0]);