forked from karan/Projects
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathprime_factorization.c
48 lines (39 loc) · 942 Bytes
/
prime_factorization.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <stdio.h>
#include <stdlib.h>
int factorize(int val, int p);
int main(int argc, char *argv[])
{
if (argc != 2) {
fprintf(stderr, "USAGE: ./prime_factorization.c NUMBER\n");
}
int N = atoi(argv[1]);
int val = N;
int p = 2;
if (val < 2) {
printf("No primes here\n");
return -1;
}
printf("Primes of %d are: ", val);
// factorize until value is 1
do {
int new_val = factorize(val, p);
// if the value was indeed factorized then, it was a prime
if (new_val != val) {
printf("%d ", p);
}
// replace val with new (factorized) value
val = new_val;
// test with following number if its also divisible
p++;
} while (val != 1);
printf("\n");
return 0;
}
// factorizes val by p
int factorize(int val, int p)
{
while (val % p == 0) {
val /= p;
}
return val;
}