long long operations are long long in time

be carefull with them...

The mapping function

y = map(x, 2, 167771, 1, 100000);

overflows so you should rewrite (and rethink) it.

This mapping function may or may not be reduced to the following function:

y = x * (out_max/GCD(out_max, in_max) ) / (in_max /GCD(out_max, in_max)) + out_min; // greatest common divider ==> e.g. 8/12 == (8/4) / (12/4)

which will simplify the numbers in the formula

unless the GCD() == 1 // in_max and out_max have no common divisor.

in this case they have no common divider so it cannot be simplified!

[think]

How to simplify it with a minimal error?

The first that comes in mind is

y = map(x, 0, 167771, 0, 999999);

note there are 2 changes. By a remapping the lower values to 0 for both in and out the formula becomes much more simple (they already were close to zero). Be aware this introduces a small error than can be "fixed" by using the constrain() function afterwards

With the two zeros the function becomes:

y = x * out_max / in_max ;

as GCD(999999, 167771) = 1, the next best thing is an approximation: 999999/167771 = 5.960499.... so that is almost 6 (with less than 1% error!)

that info would lead to the following approximation function:

y = x * 6;

range of your pot was [2 - 167771] that would map to [12 - 1006626] // no overflow!!

so to adjust the lower border we subtract 11 and the upper border is fixed with constrain(), This gives a new "mapping" function:

long mymap(long x)

{

long y = 6 * x - 11; // [1 - 1006615]

if (y > 100000L) y = 100000L; // [1 - 100000]

return y;

}

give it a try