-
Notifications
You must be signed in to change notification settings - Fork 5
/
prime_factors.c
54 lines (42 loc) · 973 Bytes
/
prime_factors.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
48
49
50
51
52
53
54
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#define MAX_FACTORS 25
typedef struct PRIME_FACTORS
{
unsigned long *factors;
unsigned long count;
} Prime_Factor;
Prime_Factor prime_factors(unsigned long n)
{
int root = (int) sqrt(n);
unsigned long *factors = (unsigned long *) malloc(MAX_FACTORS * sizeof(unsigned long));
unsigned long j = 0;
for (unsigned long i = 2; i <= root; i++) {
if (n % i == 0) {
while (n % i == 0) {
n = n / i;
factors[j++] = i;
}
}
}
if (n != 1) {
factors[j++] = n;
}
Prime_Factor factor = {
.factors = factors,
.count = j
};
return factor;
}
int main()
{
unsigned long n;
printf("%s", "Enter n: ");
scanf("%lu", &n);
Prime_Factor factor = prime_factors(n);
for (int i = 0; i < factor.count; i++) {
printf("%lu ", factor.factors[i]);
}
return 0;
}