In my computer this code takes 17 seconds (1000 millions times):
static void Main(string[] args) {
var sw = new Stopwatch(); sw.Start();
int r;
for
The efficiency may very well depend on the numbers involved. You are testing a TINY fraction of the available problem space, and all front-loaded. You are checking the first 1 million * 10 = 1 billion contiguous input combinations, but the actual problem space is approx 4.2 billion squared, or 1.8e19 combinations.
The performance of general library math operations like this needs to be amortized over the whole problem space. I'd be interested to see the results of a more normalized input distribution.