Oftentimes I encounter situations like the following:
I have two integers $x$ and $y$ in a loop. If $y$ divides evenly into $x$, then I want to find out the quotient $\ddfrac{x}{y}$ and break
out of loop. Otherwise continue
.
Now so far I was doing something like this:
Now what bothered me is that I knew for any given pair of integer $(x,y)$ there exists a quotient $q$ and remainder $r$ such that:
\[x = q\times y + r\]
and you can actually find $q$ and $r$ both at the same time using algorithms like Extended Euclidean Algorithm. So instead of checking $x \% y$ first and then computing the quotient again, we can just simply compute it once. But this meant I had to implement my own version of Extended Euclid as I didn’t know of any library functions. This isn’t a clean solution.
Today I came to know there is indeed a library function for this! It called div()
and it’s included in the cstdlib
header. div()
takes two parameters: one integer numerator and one integer denominator and returns a struct
which has the following definition:
So, now the above code becomes:
This is a much cleaner and efficient solution. There are also ldiv_t
and lldiv_t
for long
and long long
data types. Check out this link for more details!
Sharing is caring. Share this story in...
Share: Twitter Facebook LinkedIn