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