Two sum algorithm variant I need to compute the number of target values \$t\$ in the range: \$-10000 \le t \le 10000\$ (inclusive) such that there are distinct numbers \$x, y\$ in the input file that satisfy \$t= x+y\$. I have the code which does work and would like to optimize it to run it faster.

Also, we'll count the sum \$t\$ only once. If there are two \$x,y\$ pairs that add to 55, you will only increment the result once.

public static int Calculate(int start, int finish, HashSet&lt;long&gt; numbers)
{
    int result = 0;
    for (int sum = start; sum &lt;= finish; sum++)
    {
        foreach (long n in numbers)
        {
            if (numbers.Contains(sum - n) &amp;&amp; n != (sum - n))
            {
                result++;
                break;
            }
        }
    }

    return result;
}


This is an assignment and I completed it with full marks. My code is taking like 30 minutes to run against the data set of 1 million numbers. I tried to think a way to optimize my code, but couldn't get to the right thought and would appreciate some help.
There is no need to iterate over the range. Consider a pseudocode:

sort numbers from the input file into an array A
N = size of collection
result = 0
for i in [0..N)
    find largest j (j &gt; i) such that A[i] + A[j] &lt; start
    find smallest k (k &gt; i) such that A[i] + A[k] &gt; finish
    result += k - j


Each find is \$O(\log N)\$ at worst. Overall complexity is \$O(N \log N)\$ regardless of the target range.