Skip to content

Instantly share code, notes, and snippets.

@CallumWatkins
Last active February 18, 2017 16:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CallumWatkins/c1671090ed72aa956df6b453402b9363 to your computer and use it in GitHub Desktop.
Save CallumWatkins/c1671090ed72aa956df6b453402b9363 to your computer and use it in GitHub Desktop.
Calculates the sum of all the integers in the range between two integers, with the option to exclude them. License: MIT
/// <summary>
/// Calculates the sum of all the integers in the range between two integers.
/// </summary>
/// <param name="start">The starting integer.</param>
/// <param name="end">The ending integer.</param>
/// <param name="exclusive">Whether or not the <paramref name="start"/> and <paramref name="end"/> integers are excluded from the sum.</param>
/// <returns>Returns the sum of the integers in the range.</returns>
private static long SumBetween(int start, int end, bool exclusive = false)
{
if (start > end) { throw new ArgumentException("End value must be more than or equal to start value."); }
// Create long (Int64) representations of both 'start' and 'end' int parameters
long min = start;
long max = end;
// Adjust 'min' and 'max' values if the series is exclusive of the start and end values
if (exclusive)
{
min++;
max--;
if (min > max) { return 0; }
}
// Calculate the number of values in the series between the two given integers
long seriesLength = (max - min) + 1;
// Return the sum of every value in the series length
return (seriesLength * (min + max)) / 2;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment