August 21, 2010
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++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
//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; } |