Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
- //
- // Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in. Additionally, if the number is negative, return 0 (for languages that do have them).
- //
- // Note: If the number is a multiple of both 3 and 5, only count it once.
- //
- // Courtesy of projecteuler.net (Problem 1)
- #include <stdbool.h>
- #include <stdint.h>
- #include <stdlib.h>
- // very professional enterprise code
- typedef struct list list_t;
- struct list
- {
- void *elem;
- list_t *next;
- };
- list_t *LIST_EMPTY = &(list_t){0};
- static list_t *list_cons(void *elem, list_t *list)
- {
- list_t *res;
- res = calloc(1, sizeof(list_t));
- res->elem = elem;
- res->next = list;
- return res;
- }
- static int *make_int(int val)
- {
- int *i;
- i = calloc(1, sizeof(int));
- *i = val;
- return i;
- }
- static list_t *range(int from, int to)
- {
- if(from >= to)
- return LIST_EMPTY;
- return list_cons(make_int(from), range(from+1, to));
- }
- static int sum(list_t *list)
- {
- return list->elem ? *(int *)list->elem + sum(list->next) : 0;
- }
- static int *mul(int *x, int *y)
- {
- return make_int(*x * *y);
- }
- static list_t* filter(bool f(void *), list_t *list)
- {
- if(!list->elem)
- return LIST_EMPTY;
- return f(list->elem) ? list_cons(list->elem, filter(f, list->next)) : filter(f, list->next);
- }
- static bool divBy3Or5(int *num)
- {
- return !(*num % 3 && *num % 5);
- }
- int solution(int i)
- {
- return sum(filter(divBy3Or5, range(0, i)));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement