/* Problem 3: Phil Sweany's Consecutive Sum Given an integer, find all the consecutive sums leading to that integer. */ #include #include #include int main (int argc, char **argv); FILE *in, *out; int main (int argc, char **argv) { int b, S, l; /* Beginning, sum, and length of a consecutive sum */ /* This uses the formula for the sum of a consecutive arithmetic sequence: S = l/2 (2b+l-1), solving for b, S, and looping through all possible l's. */ in = fopen ("prob3.in","r"); out = fopen ("prob3.out","w"); while (1) { fscanf (in,"%d",&S); if (S==0) break; for (l=sqrt (2*S); l > 1; l--) { /* Solve for b */ b = ((double)S/l + (1-l)/2.0) +0.5; if ((S%l==0 && l%2==1) || (S%l*2==l && l%2==0)) /*Is b an integer?*/ fprintf (out,"%d %d\n",b,b+l-1); } fprintf (out,"\n"); } fclose (in); fclose (out); return EXIT_SUCCESS; }