1)
Sum := 0;
for J in 1 .. N loop
Sum := Sum + J;
end loop;
2)
Sum := ((N + 1) * N) / 2;

I’ve read that the first(left) solution is more “general” – applicable to a wide range of values - than second(right) solution. What does “general” mean – can be computed without overflow?
I think “more general” must mean “can be computed without overflow for a larger range of numbers”.
The intermediate product in (2) will overflow at 2^31 – 1 (for a 32-bit
Integeras you will get on most modern machines), which means that the largest legal result will be somewhat less than 2^30 – 1. (1) will let you continue almost as far again (if you can wait that long!)This program explores the limits:
and if you compile with
gnatmake -gnato summation.adband run it it ends withIf you leave out the
-gnato, so that GNAT doesn’t do numeric overflow checks (a regrettable default, chosen as I remember for efficiency) this happens:I suppose you could get the longer range by dividing whichever of
NandN + 1was even (one clearly must be!) by 2 before doing the multiplication.This isn’t really an Ada problem (though
-gnatomakes it easier to see when things go wrong than might happen with some other languages), and it’s certainly not a factorial! Is it possible to edit the title?