source: trunk/minix/commands/simple/factor.c@ 11

Last change on this file since 11 was 9, checked in by Mattia Monga, 14 years ago

Minix 3.1.2a

File size: 885 bytes
RevLine 
[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
9int main(argc, argv)
10int argc;
11char *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
41long first(k)
42long 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.