How can I speed up this for loop? C++


The code:

int num=999999; //or generally a very big number (like 10^6, etc.)

int sum=0;

for(int i=num; i>=1; i--) sum+=i;

So basically I want to find the sum of the num + num-1 + num-2 +...+ 1, is there any way to make for loop faster or to get rid of it entirely?

>Solution :

This seems to be a math problem.

The loop can be avoided by using a formula for the sum of the integers from 1 up to and including a positive integer n, given as

sum = n * (n + 1) / 2

Leave a Reply Cancel reply