-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecomp.c
More file actions
88 lines (70 loc) · 1.78 KB
/
decomp.c
File metadata and controls
88 lines (70 loc) · 1.78 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
// primes.c
/* Enzo Ferber : <enzo@veloxmail.com.br>
*
* Decompose into Prime Factors a given number
*
* march 27 2009
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define START 2
// used by the main() function to print the factors
int control;
/* decom ( num )
*
* @ num: number to decompose
*
* @ Return: return an int* containing all the prime factors
*/
int *decom(int num)
{
// ...
register int i;
int *primes = (int *)malloc(sizeof(int));
// Houston, we have a problem!
if (!primes)
exit(0);
// set control variable
control = 1;
// START represents the first prime number, 2
for (i = START; i <= num || num != 1; i++)
{
// ensures just an exact division
while ((num % i) == 0)
{
// I WANT MORE MEMORY, BITCH!!!
primes = (int *)realloc(primes, control * sizeof(int));
// Houston, we have a problem!
if (!primes)
exit(0);
// put the current prime factor into the list
primes[control - 1] = i;
control++;
// set new number to be divided next
num = num / i;
}
}
// return the prime list
return primes;
}
int main(int argc, char **argv)
{
// check for the correct argument
if (argc != 2)
{
// HowTo use a very complex program...
printf("Usage: %s <number>\n", argv[0]);
return 0;
}
// begin the program if the arguments are correct
register int i;
// call the function to decompose into prime factors
int *primes = decom(atoi(argv[1]));
// print prime list
for (i = 0; i < control - 1; i++)
printf("%3d: %d\n", i + 1, primes[i]);
// free the memory
free(primes);
return 0;
}