Prime Factor
This algorithm finds all prime factors of given number.
/*****Please include following header files*****/
// stdlib.h
// math.h
/***********************************************/
int* AddItemInArray(int* arr, int count, int item) {
int* newArr = (int*)malloc(sizeof(int) * (count + 1));
for (int i = 0; i < count; i++) {
newArr[i] = arr[i];
}
newArr[count] = item;
return newArr;
}
int PrimeFactor(int number, int** factors)
{
int factorsCount = 0;
while (number % 2 == 0) {
*factors = AddItemInArray(*factors, factorsCount, 2);
++factorsCount;
number /= 2;
}
for (int i = 3; i <= sqrt(number); i += 2) {
while (number % i == 0) {
*factors = AddItemInArray(*factors, factorsCount, i);
++factorsCount;
number /= i;
}
}
if (number > 2) {
*factors = AddItemInArray(*factors, factorsCount, number);
++factorsCount;
}
return factorsCount;
}
Example
int* factors = (int*)malloc(sizeof(int));
int factorsCount = PrimeFactor(488, &factors);
Output
2
2
2
61