add opendir alias
[minix.git] / commands / factor / factor.c
blob56854e9ede636de5bb4b27f29ba2c11b28b0c4da
1 /* factor - print the prime factors of a number Author: Andy Tanenbaum */
3 #include <stdlib.h>
4 #include <stdio.h>
6 int main(int argc, char **argv);
7 long first(long k);
9 int main(argc, argv)
10 int argc;
11 char *argv[];
13 /* Factor a number */
15 long i, n, flag = 0;
17 if (argc != 2 || (n = atol(argv[1])) < 2) {
18 printf("Usage: factor n (2 <= n < 2**31)\n");
19 exit(1);
21 if (n == 2) {
22 printf("2 is a prime\n");
23 exit(0);
25 while (1) {
26 i = first(n);
27 if (i == 0) {
28 if (flag == 0)
29 printf("%ld is a prime\n", n);
30 else
31 printf("%ld\n", n);
32 exit(0);
34 printf("%ld ", i);
35 n = n / i;
36 flag = 1;
41 long first(k)
42 long k;
44 /* Return the first factor of k. If it is a prime, return 0; */
46 long i;
48 if (k == 2) return(0);
49 if (k % 2 == 0) return (2);
50 for (i = 3; i <= k / 3; i += 2)
51 if (k % i == 0) return(i);
52 return(0);