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<long> numbers)
{
int result = 0;
for (int sum = start; sum <= finish; sum++)
{
foreach (long n in numbers)
{
if (numbers.Contains(sum - n) && 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.