I need the values of the 3rd grade division ie. 8/3 = 2r2
I ALSO potentially need the value of one higher ie. 8/3 = 3r-1
The result I would use would be based on the smaller absolute value of the remainder, so in this case I would use 3r-1.
Potential Results would be:
7/3 = 2r1
6/2 = 3r0
13/8 = 2r-3
etc.
Here is some code I quickly wrote. I feel like this is a bad way of going about this. Any advice?
public int lowerNumber;
public int higherNumber;
public int positiveRemainder;
public int negativeRemainder;
public void DetermineNumberAndRemainder(int u, int c)
{
positiveRemainder = u % c;
lowerNumber = Mathf.FloorToInt(u / c);
if (positiveRemainder == 0)
{
Debug.Log("ME(" + u + "," + c + ") = "
+ lowerNumber + "r" + positiveRemainder + ".");
return;
}
else
{
higherNumber = Mathf.CeilToInt(u / c);
negativeRemainder = higherNumber * c - u;
Debug.Log("ME(" + u + "," + c + ") = "
+ lowerNumber + "r" + positiveRemainder
+ " OR " + higherNumber + "r" + negativeRemainder + ".");
}
}
private static void DivWithRemainderBackwards(int u, int c)
{
int value = u / c;
int remain = (u % c);
if(remain != 0)
{
value += 1;
remain -= c;
}
Debug.Log(string.Format("{0}r{1}", value, remain));
}
(not sure if you wanted to support negative u,c values)
I think he also wants to make the decision based on what’s closer to 0, the positive remainder of the usual remainder operation and the result that’d overshoot and yield a higher quotient and negative remainder.
13/8 = 18 + 5
VS
13/8 = 28 - 3
choose the latter, as the absolute value of -3 is closer to 0 than 5.
So with a small tweak, it’s something like
public struct Result
{
public int X;
public int Y;
}
public Result PutAppropriateNameHere(int u, int c)
{
// TODO: handle c == 0
var quotient = u / c;
var remainder = u % c;
if ((c - remainder) < remainder)
{
quotient = quotient + 1;
remainder = remainder - c;
}
return new Result { X = quotient, Y = remainder };
}