C Implementation of Problem 1

View source code here on GitHub!

Includes

Solution

uint32_t p0001()
int main(int argc, char const *argv[])

Note

This function is only present in the Python test runner, or when compiling as a standalone program. It is not present when compiling for the Unity test runner.

 1/**
 2 * Project Euler Problem 1
 3 *
 4 * I know that this could be done faster with a traditional for loop, but I wanted
 5 * to see if iterators were reasonably possible in C, since it makes the prime
 6 * number infrastructure a lot easier to set up.
 7 *
 8 * Problem:
 9 *
10 * If we list all the natural numbers below 10 that are multiples of 3 or 5, we
11 * get 3, 5, 6 and 9. The sum of these multiples is 23.
12 *
13 * Find the sum of all the multiples of 3 or 5 below 1000.
14 */
15#ifndef EULER_P0001
16#define EULER_P0001
17#include <stdint.h>
18#include <inttypes.h>
19#include <stdio.h>
20#include "include/macros.h"
21#include "include/iterator.h"
22
23uint32_t EMSCRIPTEN_KEEPALIVE p0001() {
24    uint32_t answer = 0;
25    counter c = counter3(0, 1000, 3);
26    while (!c.exhausted)
27        answer += next(c);
28    c = counter3(0, 1000, 5);
29    while (!c.exhausted)
30        answer += next(c);
31    c = counter3(0, 1000, 15);
32    while (!c.exhausted)
33        answer -= next(c);
34    return answer;
35}
36
37PROGRAM_TAIL("%" PRIu32, p0001)
38#endif

Tags: c-iterator, divisibility