Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading