LargeInteger's equivalent of BigInteger's and?

136 views Asked by At

LargeInteger doesn't appear to have an equivalent function to BigInteger's and.

Since and(BigInteger val) "Returns a BigInteger whose value is (this & val). (This method returns a negative BigInteger if and only if this and val are both negative.)", I tried to follow this great answer on reproducing testBit with

static LargeInteger and(LargeInteger i, LargeInteger j) {
    return i & j;
}

but the compiler reports

error: bad operand types for binary operator '&'
    return i & j;
             ^

How can BigInteger's and be reproduced to be used on LargeInteger?

2

There are 2 answers

0
Joop Eggen On BEST ANSWER

org.jscience.mathematics.number.LargeInteger does not seem to have a similar bit-wise function and (if I have sougth the right class & version).

static LargeInteger and(LargeInteger lhs, LargeInteger rhs) {
     long l = lhs.longValue(); // Low order bits
     long r = rhs.longValue();
     long lo = l & r;

     LargeInteger hi = LargeInteger.ZERO;
     if (lhs.bitLength() > 64 && rhs.bitLength() > 64) {
         hi = and(lhs.shiftRight(64), rhs.shiftRight(64)).shiftLeft(64);
     }
     return hi.plus(lo);
}

Mind, that for a bitwise or the condition needs || instead of &&.

4
Ingo On

Judging from the documentation, there are methods for converting LargeIntegers into byte arrays, and also to create a LargeInteger from byte arrays. Hence, you can do the following:

convert operands to byte arrays
combine the individual bytes with the operator you want (&, |, ^)
convert resulting byte array back to LargeInteger

Now, correct me if I am wrong, but the original python code seems to only do n & 1. Since you have even() and odd() methods, why not use them? The following identity holds:

 large & 1 = large.odd() ? 1 : 0