-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlargest_prime_factor.c
More file actions
95 lines (75 loc) · 1.67 KB
/
Copy pathlargest_prime_factor.c
File metadata and controls
95 lines (75 loc) · 1.67 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct
{
int *array;
size_t size;
} Array;
void add_element(Array *a, int new_element)
{
a->size += 1;
a->array = (int *)realloc(a->array,a->size * sizeof(int));
a->array[a->size-1] = new_element;
// printf("array size = %d\n", (int)a->size);
}
void freeArray(Array *a)
{
free(a->array);
a->array = NULL;
}
int modulo_op(double a, int b)
{
return (int)(a - ((double)b)*floor(a/(double)b));
}
int main()
{
double test_num;
int i,j,k;
int biggest_pf;
Array prime_factors;
prime_factors.array = (int *)malloc(0);
prime_factors.size = 0;
printf("Type in a number to find its largest prime\n");
scanf("%lf", &test_num);
for (i = 2; i < test_num; i++)
{
// printf("%d\n", i);
if (modulo_op(test_num,i) == 0){
// it's a factor
if (prime_factors.size == 0)
{
add_element(&prime_factors,i);
biggest_pf = i;
// printf("array[0] = %d\n", prime_factors.array[0]);
}
else
{
// printf("here\n");
for (j = 0; j < prime_factors.size; j++)
{
// printf("i = %d, prime_factors.array[j] = %d, i %% prime_factors.array[j] = %d\n", i,
// prime_factors.array[j], i % prime_factors.array[j]);
if (modulo_op(i,prime_factors.array[j]) == 0)
{
break;
}
}
if (j == prime_factors.size)
{
add_element(&prime_factors, i);
biggest_pf = i;
printf("prime = %d\n", biggest_pf);
// sleep(0.5);
}
}
}
}
printf("List of prime factors: \n");
for(k = 0; k < prime_factors.size; k++)
{
printf("%d ", prime_factors.array[k]);
}
printf("\nbiggest prime factor = %d\n", biggest_pf);
freeArray(&prime_factors);
}