All pastes #750746 Raw Edit

Someone

public c v1 · immutable
#750746 ·published 2007-10-26 19:02 UTC
rendered paste body
#include <stdio.h>#include <stdlib.h>#include <math.h>#define NUMBER_OF_FACTORS 3int divisors(unsigned x, unsigned *list){    unsigned i;    unsigned count = 0;    unsigned index = 0;    unsigned limit;    size_t size = 20;    size_t incr = 20;    size_t new_size;    list = malloc(sizeof(unsigned) * size);    if (list == NULL)        return -1;    limit = (unsigned)sqrt(x);    for (i = 1; i <= limit; ++i) {        if (x % i == 0) {            if (index + 2 > size) {                new_size = size + incr;                list = realloc(list, sizeof(unsigned) * new_size);                if (list == NULL) {                    free(list);                    list = NULL;                    return -1;                }                size = new_size;            }            if (i == limit) {                count += 1;                list[index++] = i;            }            else {                count += 2;                list[index++] = i;                list[index++] = x / i;            }                        }    }    list = realloc(list, sizeof(unsigned) * index);    if (list == NULL) {        free(list);        list = NULL;        return -1;    }    return count;}int main(void){    unsigned triangle = 0;    int factors;    unsigned i = 1;    unsigned *divs;    while (1) {        triangle += i++;        factors = divisors(triangle, divs);        if (factors == -1) {            fputs("No more RAM\n", stderr);            exit(-1);        }        printf("%u\n", divs[0]);        if (factors > NUMBER_OF_FACTORS)            break;        else            free(divs);    }    printf("==> %u\n", triangle);    for (i = 0; i < factors; ++i)        printf("%u ", divs[i]);    printf("\n");    free(divs);    return EXIT_SUCCESS;}