We were given a simple task to come up with the most efficient way we can to sum all the numbers between a start and end point (‘from’ and ‘to’) using recursion and iteration respectively, without using the obvious formula which would be O(1).
There is no application for this, I am simply curious and challenged to see if my solution can be improved / polished more than it already is:
/* recursion */
unsigned int sum1(unsigned int from, unsigned int to) {
if (to - from < 2)
return from + (from == to ? 0 : to);
else
return from + to + sum1(from + 1, to - 1);
}
/* iteration */
unsigned int sum2(unsigned int from, unsigned int to) {
int p = to - from;
if (p == 0) return from;
int i, s, n = p / 2;
if (p % 2 == 0) s = n + from;
else {
s = 0;
n++;
}
for (i = 0; i < n; i++) {
s += from++ + to--;
}
return s;
}
I tried improving the iterative version:
I tested your version with:
This is what I see:
I tried my implementation with the same number of loops. Here’s how the improved function performed:
UPDATE
In my implementation
x = to + fromis the sum of the first and the last number in the sequence. If you consider any consecutive sequence of integers, and sum the first and last, the second and the penultimate, and so on … all these sum up to the same value. For example, in(1 ... 6), 1 + 6 = 2 + 5 = 3 + 4 = 7. However, with a sequence containing odd number of elements, you are left with the middle number which you will then have to add to the cumulative sum (that’s what the assignment following theforloop was doing.Also, note that this is still
O(n). I realized after I initially posted my answer that my approach can actually be done in constant time. Here’s the updated code:I ran this with the same number of loops as the earlier tests. Here’s what I saw:
I’m not sure if this can be considered a variation of the formula for your purposes. In any case, it was an interesting exercise for me.