Skip to content

Instantly share code, notes, and snippets.

@meylingtaing
Last active March 27, 2016 23:20
Show Gist options
  • Save meylingtaing/aab5f9658c7c08e7c1ec to your computer and use it in GitHub Desktop.
Save meylingtaing/aab5f9658c7c08e7c1ec to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int get_divisors(int, int **);
int main(void) {
int *divisors;
int num_divisors = get_divisors(100, &divisors);
int i;
for (i = 0; i < num_divisors; i++) {
printf("%d ", divisors[i]);
}
printf("\n");
free(divisors);
return 0;
}
/* get_divisors: Need to pass in a pointer to an array of integers */
int get_divisors(int n, int **result_ptr) {
int num_divisors = 0;
int *result = malloc(sizeof(int) * 100);
// 1 is always in the result
result[num_divisors++] = 1;
if (n != 1) {
result[num_divisors++] = n;
}
int max = ceil(sqrt(n));
int divisor = 2;
while (divisor <= max) {
if (n % divisor == 0) {
result[num_divisors++] = divisor;
int other_divisor = n / divisor;
if (other_divisor > divisor)
result[num_divisors++] = other_divisor;
}
divisor++;
}
*result_ptr = result;
// Return number of divisors
return num_divisors;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment