insane_goat

2017-03-10 04:21:10 UTC

I wrote this small program to find consecutive integers up to the target. I

am quite sure that there are some ways to speed it up, can anyone suggest

improvements?

-- begin --

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

/*

* Find consecutive integers which add up to target

*/

int main(int argc, char *argv[])

{

if (argc < 2) {

fprintf(stderr, "usage: %s <target>\n", argv[0]);

return EXIT_FAILURE;

}

const unsigned target = (unsigned) atoi(argv[1]);

const unsigned max = target / 2;

const unsigned max_consecs = max;

unsigned answer;

unsigned *nums;

if ((nums = calloc(max_consecs, sizeof(int))) == NULL) {

perror("calloc");

return EXIT_FAILURE;

}

for (unsigned begin = 1; begin < max; ++begin) {

for (unsigned consecs = 2; consecs < max_consecs; ++consecs) {

answer = 0;

memset(nums, 0, max_consecs * sizeof(int));

for (unsigned i = 0; i < consecs; ++i) {

nums[i] = i + begin;

if ((answer += nums[i]) > target) {

break;

}

}

if (answer == target) {

for (unsigned i = 0; nums[i] != 0; ++i) {

if (i != 0) {

putchar(' ');

}

printf("%d", nums[i]);

}

putchar('\n');

free(nums);

return EXIT_SUCCESS;

} else if (answer > target) {

break;

}

}

}

puts("no answer");

free(nums);

return EXIT_FAILURE;

}

-- end --

am quite sure that there are some ways to speed it up, can anyone suggest

improvements?

-- begin --

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

/*

* Find consecutive integers which add up to target

*/

int main(int argc, char *argv[])

{

if (argc < 2) {

fprintf(stderr, "usage: %s <target>\n", argv[0]);

return EXIT_FAILURE;

}

const unsigned target = (unsigned) atoi(argv[1]);

const unsigned max = target / 2;

const unsigned max_consecs = max;

unsigned answer;

unsigned *nums;

if ((nums = calloc(max_consecs, sizeof(int))) == NULL) {

perror("calloc");

return EXIT_FAILURE;

}

for (unsigned begin = 1; begin < max; ++begin) {

for (unsigned consecs = 2; consecs < max_consecs; ++consecs) {

answer = 0;

memset(nums, 0, max_consecs * sizeof(int));

for (unsigned i = 0; i < consecs; ++i) {

nums[i] = i + begin;

if ((answer += nums[i]) > target) {

break;

}

}

if (answer == target) {

for (unsigned i = 0; nums[i] != 0; ++i) {

if (i != 0) {

putchar(' ');

}

printf("%d", nums[i]);

}

putchar('\n');

free(nums);

return EXIT_SUCCESS;

} else if (answer > target) {

break;

}

}

}

puts("no answer");

free(nums);

return EXIT_FAILURE;

}

-- end --

--

insane_goat

insane_goat