Sum of Integers in a Range

Problem

Write a function to compute the sum of integers between two given integer values.

Solution

The naive solution is to loop by going from the lower integer ending at the higher integer while calculating the sum. The other solution is compute the sum using the following formula Sum (1..n) = n (n + 1)/2

Code

Here is the code in C++

//Includes
#include <iostream>

//STD
using namespace std;

//Assume n <= m
int LoopMethod(int n, int m)
{
	int sum = 0;

	for (int i = n; i <= m; i++)
	{
		sum += i;
	}

	return sum;
}

//Assume n <= m
int FormulaMethod(int n, int m)
{
	//Sum the integers from 1 to m then subtract the
	//sum of integers from 1 to n - 1
	return (m * (m + 1)/2) - ((n-1) * ((n-1) + 1)/2);
}

//Main function
void main()
{
	//Test functions
	cout << LoopMethod(33, 100) << endl;
	cout << FormulaMethod(33, 100) << endl;
}
Tags:

Leave a Reply