By the way, here is a more efficient solution:
int calc(int from, int to) { if (from == 0) return to * (to+1) / 2; else return calc(0, to) - calc(0, from); }
This is even recursive! Well, until you simplify it further
int calc(int from, int to) { return ( to * (to+1) - from * (from+1) ) / 2; }
This is because f (n) = n + ... + 3 + 2 + 1 = n (n + 1) / 2
source share