Advertisement
Guest User

Euler1

a guest
Apr 4th, 2019
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.26 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stdint.h>
  4.  
  5. // This function calculates the sum of all the
  6. // numbers below a certain treshold that are
  7. // a multiple of one of the given numbers.
  8. // argv[1] is the treshold.
  9. // Every argument after is a multiple-number.
  10. // The solution to the problem can be achieved
  11. //  with argv = [10, 3, 5]
  12. int main(int argc, char* argv[]) {
  13.     if (argc < 2) {
  14.         fprintf(stderr, "At least 2 arguments are required.\n");
  15.         return 1;
  16.     }
  17.     uint32_t sum = 0;
  18.     for (char* s_treshhold = argv[1]; *s_treshhold; s_treshhold += 1) {
  19.         if (!(*s_treshhold >= '0' && *s_treshhold <= '9')) {
  20.             fprintf(stderr, "Arguments may only be valid numbers\n");
  21.             return 1;
  22.         }
  23.     }
  24.     uint32_t treshold = strtol(argv[1], NULL, 10);
  25.     uint32_t* mult_args = calloc(argc - 2, sizeof(uint32_t));
  26.     for (int i = 2; i < argc; i += 1) {
  27.         for (char* s_treshhold = argv[i]; *s_treshhold; s_treshhold += 1) {
  28.             if (!(*s_treshhold >= '0' && *s_treshhold <= '9')) {
  29.                 fprintf(stderr, "Arguments may only be valid numbers\n");
  30.                 free(mult_args);
  31.                 return 1;
  32.             }
  33.         }
  34.         mult_args[i-2] = strtol(argv[i], NULL, 10);
  35.     }
  36.     for (int i = 0; i < argc - 2; i += 1) {
  37.         if (mult_args[i] == 0) {
  38.             fprintf(stderr, "Arguments may not be 0.\n");
  39.             return 1;
  40.         }
  41.     }
  42.     for (uint32_t i = 0; i < treshold; i += 1) {
  43.         for (int j = 0; j < argc - 2; j += 1) {
  44.             if (i % mult_args[j] == 0) {
  45.                 uint32_t overflow_check = i + sum;
  46.                 if (overflow_check < sum) {
  47.                     fprintf(stderr, "An overflow has occured.\n");
  48.                     fprintf(stderr, "Resulting value is at least %u large", UINT32_MAX);
  49.                     free(mult_args);
  50.                     return 1;
  51.                 }
  52.                 sum += i;
  53.                 break; // Break inner loop.
  54.             }
  55.         }
  56.     }
  57.     printf("The sum of all multiples of [");
  58.     for (int i = 0; i < argc - 3; i += 1) {
  59.         printf("%d,", mult_args[i]);
  60.     }
  61.     printf("%u] below %u is: %u.\n", mult_args[argc - 3], treshold, sum);
  62.     free(mult_args);
  63.     return 0;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement