Determining the Remainder

algorithmsarithmetic

Is it possible to calculate the remainder of two given values with merely addition, subtraction, multiplication, and division? Is there an algorithm or formula if it is even possible?

For instance, say we have two values: 100 and 30. If we divide 100 by 30, we get 3.333.... But is there any way to reach 0.333... (without knowing from the get go how many wholes are included)?

To further illustrate what I mean, and sticking with the example above, one way to find the remainder would be the following formula: 100 / 30 / 10 * 30 = 0.333... BUT this obviously does not work for any two given numbers.

Some more examples (The values in the brackets are the values I am after):

100 / 40 = 2.5 (0.5)
450 / 50 = 9 (0)
11 / 4 = 2.75 (75)

Sorry, if this question is not clear. It is based on a programming challenge I have encountered. I want to use only CSS to calculate the remainder of a text's line height, given a specific vertical offset of the text. For instance, the height of the window might be 100, whereas the line height would be 30. But CSS has no function to easily determine the remainder, and I cannot use loops or recursion (i.e. 100 - 30 - 30 - 30 - 30 < 0), nor conditional (i.e. if N < 0, do…).

My math is awful. But I am wondering whether or not it is mathematically possible?

Best Answer

I don't know whether it is possible to make the "remainder in integral division" in CSS using "thinking out of the box" somehow, but mathematically it cannot be done using just addition, subtraction, multiplication and division.

Namely, a function $f(x,y)$ made up of addition, subtraction, multiplication and division is a rational function (a quotient of two real polynomials in two variables $x$ and $y$).

Now suppose that $\text{remainder}(x,y)=\frac{P(x,y)}{Q(x,y)}$ where $P$ and $Q$ are polynomials. Fix $y=2$ and then we would have $\text{remainder}(x,2)=\frac{P(x,2)}{Q(x,2)}=\frac{p(x)}{q(x)}$ where $p(x)=P(x,2)$ and $q(x)=Q(x,2)$ - polynomials in one variable. Knowing that:

$$\frac{p(n)}{q(n)}=0$$

for each even $n$, we can conclude that $p=0$ (zero polynomial). However, this is then inconsistent with the other requirement, which is that:

$$\frac{p(n)}{q(n)}=1$$

for each odd $n$.

Note: I can see that CSS spec for $\text{calc}()$ says that, ultimately, when the result of CSS calculation is assigned to an attribute, it may be rounded if that attribute requires an integer. Rounding is similar to truncation ($\text{round}(x)=\text{ceil}(x+0.5)$) and truncation can be used for integral division ($\text{remainder}(x, y)=x-y\times\text{ceil}(x/y)$) so maybe this can be all cobbled together somehow - but I wouldn't know myself how to do that, as I am not a CSS expert...

Related Question