The problem
Create a operate named divisors
/Divisors
that takes an integer n > 1
and returns an array with all the integer’s divisors(apart from 1 and the quantity itself), from smallest to largest. If the quantity is prime return the string ‘(integer) is prime’ (null
in C#) (use Both String a
in Haskell and Outcome<Vec<u32>, String>
in Rust).
Instance:
divisors(12); // leads to {2, 3, 4, 6}
divisors(25); // leads to {5}
divisors(13); // leads to NULL
The answer in C
Possibility 1:
#embrace <stddef.h>
void divisors(unsigned n, size_t *z, unsigned *array) {
*z = 0;
for (int i = 2; i <= (n / 2); i++) {
if (n % i == 0)
array[(*z)++] = i;
}
}
Possibility 2:
#embrace <stddef.h>
void divisors(unsigned n, size_t *size, unsigned array[]) {
int i;
int j = 0;
for (i = 2; i < (int) n; i++) {
if (n % i == 0) {
array[j] = i;
j++;
}
}
*size = (size_t) j;
}
Possibility 3:
#embrace <stddef.h>
void divisors(unsigned n, size_t *z, unsigned *array) {
int len = 0;
for (unsigned i = 2; i < n; i++) {
if (n % i == 0) array[len++] = i;
}
*z = len;
}
Check circumstances to validate our resolution
#embrace <criterion/criterion.h>
#embrace <stddef.h>
extern void tester(unsigned n, size_t size, const unsigned anticipated[length]);
Check(Sample_Tests, should_pass_all_tests)
{
{ unsigned n = 15; const unsigned anticipated[2] = {3, 5}; tester(n, 2, anticipated); }
{ unsigned n = 253; const unsigned anticipated[2] = {11, 23}; tester(n, 2, anticipated); }
{ unsigned n = 24; const unsigned anticipated[6] = {2, 3, 4, 6, 8, 12}; tester(n, 6, anticipated); }
{ unsigned n = 25; const unsigned anticipated[1] = {5}; tester(n, 1, anticipated); }
{ unsigned n = 13; const unsigned *anticipated = NULL; tester(n, 0, anticipated); }
{ unsigned n = 3; const unsigned *anticipated = NULL; tester(n, 0, anticipated); }
{ unsigned n = 29; const unsigned *anticipated = NULL; tester(n, 0, anticipated); }
}