Although it is not clear what limitations may be related to how you achieve the largest discrete series of numbers, but if you are able to, passing a simple array to store discrete numbers and storing the current amount in your function can simplify the process. For example, passing an array a long with the current j to the function and returning the number of elements that make up the sum in the array can be performed using the following:
int largest_discrete_sum (int *a, int j) { int n, sum = 0; for (n = 1;; n++) { a[n-1] = n, sum += n; if (n * (n + 1) / 2 > j) break; } a[sum - j - 1] = 0; /* zero the index holding excess */ return n; }
Combining in a short test program will look like this:
#include <stdio.h> int largest_discrete_sum(int *a, int j); int main (void) { int i, idx = 0, v = 50; int a[v]; idx = largest_discrete_sum (a, v); printf ("\n largest_discrete_sum '%d'\n\n", v); for (i = 0; i < idx; i++) if (a[i]) printf (!i ? " %2d" : " +%2d", a[i]); printf (" = %d\n\n", v); return 0; } int largest_discrete_sum (int *a, int j) { int n, sum = 0; for (n = 1;; n++) { a[n-1] = n, sum += n; if (n * (n + 1) / 2 > j) break; } a[sum - j - 1] = 0; /* zero the index holding excess */ return n; }
Usage / Output Example
$ ./bin/largest_discrete_sum largest_discrete_sum '50' 1 + 2 + 3 + 4 + 6 + 7 + 8 + 9 +10 = 50
I apologize if I missed the restriction on the choice of discrete values somewhere, but, approaching in this way, you are guaranteed to get the largest number of discrete values that will be equal to your sum. Let me know if you have any questions.
David C. Rankin
source share