Example 1 — Loop versus formula
Both compute 1 + 2 + ... + 1000.
#include <stdio.h>
int main(void) {
long long n = 1000, sum = 0, adds = 0;
for (long long i = 1; i <= n; i++) {
sum += i;
adds++;
}
printf("loop: %lld in %lld additions\n", sum, adds);
long long f = n * (n + 1) / 2;
printf("formula: %lld in 1 step\n", f);
return 0;
} How It Works
- Both give 500500, so they are equally correct.
- The loop does work proportional to n; the formula does constant work.
- At n = 10^9 the difference becomes the whole story.
