summary refs log tree commit diff stats
path: root/c/sum-of-multiples/src
diff options
context:
space:
mode:
Diffstat (limited to 'c/sum-of-multiples/src')
-rw-r--r--c/sum-of-multiples/src/sum_of_multiples.c17
-rw-r--r--c/sum-of-multiples/src/sum_of_multiples.h9
2 files changed, 26 insertions, 0 deletions
diff --git a/c/sum-of-multiples/src/sum_of_multiples.c b/c/sum-of-multiples/src/sum_of_multiples.c
new file mode 100644
index 0000000..9ad1eb1
--- /dev/null
+++ b/c/sum-of-multiples/src/sum_of_multiples.c
@@ -0,0 +1,17 @@
+#include "sum_of_multiples.h"
+#include <stdlib.h>
+#include <stdbool.h>
+
+unsigned int sum(const unsigned int *factors,
+                 const size_t number_of_factors, const unsigned int limit) {
+    unsigned int total = 0;
+    bool *seen = calloc(limit, sizeof(*seen));
+    for (size_t idx = 0; idx < number_of_factors; idx++)
+        for (size_t num = 0; num < limit; num++)
+            // factors[idx] shouldn't be 0. (% fails)
+            if (!seen[num] && factors[idx] && !(num % factors[idx])) {
+                total += num;
+                seen[num] = true;
+            }
+    return total;
+}
diff --git a/c/sum-of-multiples/src/sum_of_multiples.h b/c/sum-of-multiples/src/sum_of_multiples.h
new file mode 100644
index 0000000..35dd799
--- /dev/null
+++ b/c/sum-of-multiples/src/sum_of_multiples.h
@@ -0,0 +1,9 @@
+#ifndef SUM_OF_MULTIPLES_H
+#define SUM_OF_MULTIPLES_H
+
+#include <stddef.h>
+
+unsigned int sum(const unsigned int *factors,
+                 const size_t number_of_factors, const unsigned int limit);
+
+#endif