Skip to content

How to Find the Divisors in C

The challenge

Create a function named divisors/Divisors that takes an integer n > 1 and returns an array with all of the integer’s divisors(except for 1 and the number itself), from smallest to largest. If the number is prime return the string ‘(integer) is prime’ (null in C#) (use Either String a in Haskell and Result<Vec<u32>, String> in Rust).

Example:

divisors(12); // results in {2, 3, 4, 6} divisors(25); // results in {5} divisors(13); // results in NULL
Code language: C++ (cpp)

The solution in C

Option 1:

#include <stddef.h> void divisors(unsigned n, size_t *z, unsigned *array) { *z = ; for (int i = 2; i <= (n / 2); i++) { if (n % i == ) array[(*z)++] = i; } }
Code language: C++ (cpp)

Option 2:

#include <stddef.h> void divisors(unsigned n, size_t *length, unsigned array[]) { int i; int j = ; for (i = 2; i < (int) n; i++) { if (n % i == ) { array[j] = i; j++; } } *length = (size_t) j; }
Code language: C++ (cpp)

Option 3:

#include <stddef.h> void divisors(unsigned n, size_t *z, unsigned *array) { int len = ; for (unsigned i = 2; i < n; i++) { if (n % i == ) array[len++] = i; } *z = len; }
Code language: C++ (cpp)

Test cases to validate our solution

#include <criterion/criterion.h> #include <stddef.h> extern void tester(unsigned n, size_t length, const unsigned expected[length]); Test(Sample_Tests, should_pass_all_tests) { { unsigned n = 15; const unsigned expected[2] = {3, 5}; tester(n, 2, expected); } { unsigned n = 253; const unsigned expected[2] = {11, 23}; tester(n, 2, expected); } { unsigned n = 24; const unsigned expected[6] = {2, 3, 4, 6, 8, 12}; tester(n, 6, expected); } { unsigned n = 25; const unsigned expected[1] = {5}; tester(n, 1, expected); } { unsigned n = 13; const unsigned *expected = NULL; tester(n, , expected); } { unsigned n = 3; const unsigned *expected = NULL; tester(n, , expected); } { unsigned n = 29; const unsigned *expected = NULL; tester(n, , expected); } }
Code language: C++ (cpp)

See also  How to Return the Closest Number Multiple of 10 in C
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x