Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdint.h>
- // This function calculates the sum of all the
- // numbers below a certain treshold that are
- // a multiple of one of the given numbers.
- // argv[1] is the treshold.
- // Every argument after is a multiple-number.
- // The solution to the problem can be achieved
- // with argv = [10, 3, 5]
- int main(int argc, char* argv[]) {
- if (argc < 2) {
- fprintf(stderr, "At least 2 arguments are required.\n");
- return 1;
- }
- uint32_t sum = 0;
- for (char* s_treshhold = argv[1]; *s_treshhold; s_treshhold += 1) {
- if (!(*s_treshhold >= '0' && *s_treshhold <= '9')) {
- fprintf(stderr, "Arguments may only be valid numbers\n");
- return 1;
- }
- }
- uint32_t treshold = strtol(argv[1], NULL, 10);
- uint32_t* mult_args = calloc(argc - 2, sizeof(uint32_t));
- for (int i = 2; i < argc; i += 1) {
- for (char* s_treshhold = argv[i]; *s_treshhold; s_treshhold += 1) {
- if (!(*s_treshhold >= '0' && *s_treshhold <= '9')) {
- fprintf(stderr, "Arguments may only be valid numbers\n");
- free(mult_args);
- return 1;
- }
- }
- mult_args[i-2] = strtol(argv[i], NULL, 10);
- }
- for (int i = 0; i < argc - 2; i += 1) {
- if (mult_args[i] == 0) {
- fprintf(stderr, "Arguments may not be 0.\n");
- return 1;
- }
- }
- for (uint32_t i = 0; i < treshold; i += 1) {
- for (int j = 0; j < argc - 2; j += 1) {
- if (i % mult_args[j] == 0) {
- uint32_t overflow_check = i + sum;
- if (overflow_check < sum) {
- fprintf(stderr, "An overflow has occured.\n");
- fprintf(stderr, "Resulting value is at least %u large", UINT32_MAX);
- free(mult_args);
- return 1;
- }
- sum += i;
- break; // Break inner loop.
- }
- }
- }
- printf("The sum of all multiples of [");
- for (int i = 0; i < argc - 3; i += 1) {
- printf("%d,", mult_args[i]);
- }
- printf("%u] below %u is: %u.\n", mult_args[argc - 3], treshold, sum);
- free(mult_args);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement