I'm teaching myself algorithms and I'm sorry if my title is incorrect! I don't understand how to implement this in Java.
if x = 0:
return (q,r) = (0,0)
(q, r) = divide(⌊x/2⌋, y)
q=2·q,
r=2·r
if x is odd: r=r+1
if r≥y: r=r−y, q=q+1
return (q, r)
I don't know how to implement the following parts in Java.
(q,r)=(0,0)
(q,r)=divide(⌊x/2⌋, y)
return (q,r)
Although Java lacks built-in support for tuples, good news is that you do not have to use tuples to implement this algorithm, except for the return value. Two regular int
variables r
and q
will do.
// (q,r)=(0,0)
int q = 0, r = 0;
// (q,r)=divide(⌊x/2⌋, y)
q = (x/2) / y;
r = (x/2) % y;
Returning is a bit tricky, because you have to return two values. Idiomatic way of doing it in Java is defining a class:
class QandR {
private final int q;
private final int r;
public QandR(int q, int r) {
this.q = q;
this.r = r;
}
}
Now you can return new QandR(q, r)
from your method.
You could use either an array or a class instance to contain and return more than one values. E.g.(q,r)
where both q
and r
are of type int
int[] qrTuple = new int[2]; // zero initialized
or
class QrTuple {
int q, r;
QR(int q, int r) {
this.q = q;
this.r = r;
}
}
and then
QrTuple qrTuple = new QrTuple(0, 0);
in both cases you can do at the end of a method :
return qrTuple;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With