1410
|
1 /* factor.c - Factor integers
|
|
2 *
|
|
3 * Copyright 2014 Rob Landley <rob@landley.net>
|
|
4 *
|
|
5 * No standard, but it's in coreutils
|
|
6
|
|
7 USE_FACTOR(NEWTOY(factor, 0, TOYFLAG_USR|TOYFLAG_BIN))
|
|
8
|
|
9 config FACTOR
|
|
10 bool "factor"
|
|
11 default y
|
|
12 help
|
|
13 usage: factor NUMBER...
|
|
14
|
|
15 Factor integers.
|
|
16 */
|
|
17
|
|
18 #include "toys.h"
|
|
19
|
|
20 static void factor(char *s)
|
|
21 {
|
|
22 long l, ll;
|
|
23
|
|
24 l = strtol(s, &s, 0);
|
|
25 if (*s) {
|
|
26 error_msg("%s: not integer");
|
|
27 return;
|
|
28 }
|
|
29
|
|
30 printf("%ld:", l);
|
|
31
|
|
32 // Negative numbers have -1 as a factor
|
|
33 if (l < 0) {
|
|
34 printf(" -1");
|
|
35 l *= -1;
|
|
36 }
|
|
37
|
|
38 // Deal with 0 and 1 (and 2 since we're here)
|
|
39 if (l < 3) {
|
|
40 printf(" %ld\n", l);
|
|
41 return;
|
|
42 }
|
|
43
|
|
44 // Special case factors of 2
|
|
45 while (l && !(l&1)) {
|
|
46 printf(" 2");
|
|
47 l >>= 1;
|
|
48 }
|
|
49
|
|
50 // test odd numbers.
|
|
51 for (ll=3; ;ll += 2) {
|
|
52 if (ll*ll>l) {
|
|
53 if (l>1) printf(" %ld", l);
|
|
54 break;
|
|
55 }
|
|
56 while (!(l%ll)) {
|
|
57 printf(" %ld", ll);
|
|
58 l /= ll;
|
|
59 }
|
|
60 }
|
|
61 xputc('\n');
|
|
62 }
|
|
63
|
|
64 void factor_main(void)
|
|
65 {
|
|
66 if (toys.optc) {
|
|
67 char **ss;
|
|
68
|
|
69 for (ss = toys.optargs; *ss; ss++) factor(*ss);
|
|
70 } else for (;;) {
|
|
71 char *s = 0;
|
|
72 size_t len = 0;
|
|
73
|
|
74 if (-1 == getline(&s, &len, stdin)) break;
|
|
75 factor(s);
|
|
76 }
|
|
77 }
|