Create an algorithm that asks the user for two positive numbers, call them “first” and “last”, and prints the sum of all the numbers between first [closed]

This doesn’t concern the code itself, but rather efficiency: This can easily be solved in constant time. Thanks to Gauss we know:

sum from 0 to N is: N * (N + 1) / 2

We can simply calculate the sum from first to last using that formula. Simply substract the sum from 0 to first – 1 from the sum from 0 to last:

int sum = last * (last + 1) / 2 - (first - 1) * (first) / 2;

Thanks to @MOehm for pointing out some mistakes in my answer.

Leave a Comment