title: Finding overlapping region between two ranges of integers
body: <p>I am making a complex algorithm in C# in which one step is to compare 2 very large lists of ranges and finding out the overlapping region. I have tried a lot of ways to find them, but m not sure if I am covering all possibilities. Also my algo on this step is taking too long with huge lists.</p>
  <p><strong>Example:</strong></p>
  <p><strong>range 1 = 1-400</strong></p>
  <p><strong>range 2 = 200-600</strong></p>
  <p>So when I want to check overlap between these two ranges I should get the answer = 200.</p>
  <p>Because total 200 numbers are overlapping between these two ranges. So this is how I want the answer, I want the exact number of integers that are overlapping between two ranges.</p>
  <p><strong>Example of Lists:</strong></p>
  <p>List1 : 1-400, 401-800, 801-1200 and so on...<br />
  List2 : 10240-10276, 10420  10456, 11646-11682 and so on...</p>
  <p>Now I have to compare each range of list1 with each range of list2, and find out if a certain range of list1 overlaps with any of the range of list2 and if yes then what is the overlapping answer? These are just sample values for the purposes of understanding.</p>
  <p>I only need a simple and most efficient/fast formula to find out the overlap answer between 2 ranges. I can manage the rest of the loop algorithm.</p>
  <p><strong>Example formula</strong> :</p>
  <pre><code>var OverlappingValue = FindOverlapping(range1.StartValue, range1.EndValue,range2.StartValue, range2.EndValue);
  </code></pre>
  <p>and if the two ranges are not overlapping at all, then function must return 0.</p>
  <p>PS: I didn't post my code because it's really complicated with a lot of conditions, I only need one simple formula.</p>