Rev | Line | |
---|
[9] | 1 | /* factor - print the prime factors of a number Author: Andy Tanenbaum */
|
---|
| 2 |
|
---|
| 3 | #include <stdlib.h>
|
---|
| 4 | #include <stdio.h>
|
---|
| 5 |
|
---|
| 6 | _PROTOTYPE(int main, (int argc, char **argv));
|
---|
| 7 | _PROTOTYPE(long first, (long k));
|
---|
| 8 |
|
---|
| 9 | int main(argc, argv)
|
---|
| 10 | int argc;
|
---|
| 11 | char *argv[];
|
---|
| 12 | {
|
---|
| 13 | /* Factor a number */
|
---|
| 14 |
|
---|
| 15 | long i, n, flag = 0;
|
---|
| 16 |
|
---|
| 17 | if (argc != 2 || (n = atol(argv[1])) < 2) {
|
---|
| 18 | printf("Usage: factor n (2 <= n < 2**31)\n");
|
---|
| 19 | exit(1);
|
---|
| 20 | }
|
---|
| 21 | if (n == 2) {
|
---|
| 22 | printf("2 is a prime\n");
|
---|
| 23 | exit(0);
|
---|
| 24 | }
|
---|
| 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);
|
---|
| 33 | }
|
---|
| 34 | printf("%ld ", i);
|
---|
| 35 | n = n / i;
|
---|
| 36 | flag = 1;
|
---|
| 37 | }
|
---|
| 38 | }
|
---|
| 39 |
|
---|
| 40 |
|
---|
| 41 | long first(k)
|
---|
| 42 | long k;
|
---|
| 43 | {
|
---|
| 44 | /* Return the first factor of k. If it is a prime, return 0; */
|
---|
| 45 |
|
---|
| 46 | long i;
|
---|
| 47 |
|
---|
| 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);
|
---|
| 53 | }
|
---|
Note:
See
TracBrowser
for help on using the repository browser.