factor.c revision 1.26
1/* $OpenBSD: factor.c,v 1.26 2016/01/07 16:00:32 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 <math.h> 59#include <stdio.h> 60#include <stdlib.h> 61#include <string.h> 62#include <unistd.h> 63 64#include "primes.h" 65 66/* 67 * prime[i] is the (i+1)th prime. 68 * 69 * We are able to sieve 2^32-1 because this byte table yields all primes 70 * up to 65537 and 65537^2 > 2^32-1. 71 */ 72extern const ubig prime[]; 73extern const ubig *pr_limit; /* largest prime in the prime array */ 74extern const char pattern[]; 75extern const int pattern_size; 76 77void pr_fact(u_int64_t); /* print factors of a value */ 78void pr_bigfact(u_int64_t); 79__dead void usage(void); 80 81int 82main(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, "")) != -1) { 92 switch (ch) { 93 case '?': 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 = strtouq(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 = strtouq(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 */ 155void 156pr_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 */ 204void 205pr_bigfact(u_int64_t val) /* Factor this value. */ 206{ 207 ubig start, stop, factor; 208 char *q; 209 const ubig *p; 210 ubig fact_lim, mod; 211 char *tab_lim; 212 char table[TABSIZE]; /* Eratosthenes sieve of odd numbers */ 213 214 start = *pr_limit + 2; 215 stop = (ubig)sqrt((double)val); 216 if ((stop & 0x1) == 0) 217 stop++; 218 /* 219 * Following code barely modified from that in primes(6) 220 * 221 * we shall sieve a bytemap window, note primes and move the window 222 * upward until we pass the stop point 223 */ 224 while (start < stop) { 225 /* 226 * factor out 3, 5, 7, 11 and 13 227 */ 228 /* initial pattern copy */ 229 factor = (start%(2*3*5*7*11*13))/2; /* starting copy spot */ 230 memcpy(table, &pattern[factor], pattern_size-factor); 231 /* main block pattern copies */ 232 for (fact_lim = pattern_size - factor; 233 fact_lim + pattern_size <= TABSIZE; fact_lim += pattern_size) { 234 memcpy(&table[fact_lim], pattern, pattern_size); 235 } 236 /* final block pattern copy */ 237 memcpy(&table[fact_lim], pattern, TABSIZE-fact_lim); 238 239 if (stop-start > TABSIZE+TABSIZE) { 240 tab_lim = &table[TABSIZE]; /* sieve it all */ 241 fact_lim = (int)sqrt( 242 (double)(start)+TABSIZE+TABSIZE+1.0); 243 } else { 244 tab_lim = &table[(stop - start)/2]; /* partial sieve */ 245 fact_lim = (int)sqrt((double)(stop) + 1.0); 246 } 247 /* sieve for factors >= 17 */ 248 factor = 17; /* 17 is first prime to use */ 249 p = &prime[7]; /* 19 is next prime, pi(19)=7 */ 250 do { 251 /* determine the factor's initial sieve point */ 252 mod = start % factor; 253 if (mod & 0x1) 254 q = &table[(factor-mod)/2]; 255 else 256 q = &table[mod ? factor-(mod/2) : 0]; 257 /* sieve for our current factor */ 258 for ( ; q < tab_lim; q += factor) { 259 *q = '\0'; /* sieve out a spot */ 260 } 261 } while ((factor=(ubig)(*(p++))) <= fact_lim); 262 263 /* 264 * use generated primes 265 */ 266 for (q = table; q < tab_lim; ++q, start+=2) { 267 if (*q) { 268 if (val % start == 0) { 269 do { 270 (void)printf(" %lu", (unsigned long) start); 271 val /= start; 272 } while ((val % start) == 0); 273 (void)fflush(stdout); 274 stop = (ubig)sqrt((double)val); 275 if ((stop & 0x1) == 0) 276 stop++; 277 } 278 } 279 } 280 } 281 if (val > 1) 282 printf(" %llu", val); 283} 284 285 286void 287usage(void) 288{ 289 (void)fprintf(stderr, "usage: factor [number ...]\n"); 290 exit (1); 291} 292