Advertisement
Guest User

Untitled

a guest
Aug 16th, 2021
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.66 KB | None | 0 0
  1.  // 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.
  2. //
  3. // 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).
  4. //
  5. // Note: If the number is a multiple of both 3 and 5, only count it once.
  6. //
  7. // Courtesy of projecteuler.net (Problem 1)
  8.  
  9. #include <stdbool.h>
  10. #include <stdint.h>
  11. #include <stdlib.h>
  12.  
  13. // very professional enterprise code
  14.  
  15. typedef struct list list_t;
  16.  
  17. struct list
  18. {
  19.     void   *elem;
  20.     list_t *next;
  21. };
  22.  
  23. list_t *LIST_EMPTY = &(list_t){0};
  24.  
  25. static list_t *list_cons(void *elem, list_t *list)
  26. {
  27.     list_t *res;
  28.  
  29.     res = calloc(1, sizeof(list_t));
  30.     res->elem = elem;
  31.     res->next = list;
  32.  
  33.     return res;
  34. }
  35.  
  36. static int *make_int(int val)
  37. {
  38.     int *i;
  39.  
  40.     i = calloc(1, sizeof(int));
  41.  
  42.     *i = val;
  43.    
  44.     return i;
  45. }
  46.  
  47. static list_t *range(int from, int to)
  48. {
  49.     if(from >= to)
  50.         return LIST_EMPTY;
  51.     return list_cons(make_int(from), range(from+1, to));
  52. }
  53.  
  54. static int sum(list_t *list)
  55. {
  56.     return list->elem ? *(int *)list->elem + sum(list->next) : 0;
  57. }
  58.  
  59. static int *mul(int *x, int *y)
  60. {
  61.     return make_int(*x * *y);
  62. }
  63.  
  64. static list_t* filter(bool f(void *), list_t *list)
  65. {
  66.     if(!list->elem)
  67.         return LIST_EMPTY;
  68.     return f(list->elem) ? list_cons(list->elem, filter(f, list->next)) : filter(f, list->next);
  69. }
  70.  
  71. static bool divBy3Or5(int *num)
  72. {
  73.     return !(*num % 3 && *num % 5);
  74. }
  75.  
  76. int solution(int i)
  77. {
  78.     return sum(filter(divBy3Or5, range(0, i)));
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement