Search code examples
javamathlong-integerlogarithm

Cannot find the value of X in Java 42L + -37L * X == 17206538691L


Long AAA = 42L;
Long BBB = -37L;
Long TTT = 17206538691L;

problem is don't know value that X should be for equation:

AAA + BBB * X == TTT

this should find the value for X but it's off

Long X = TTT / BBB - AAA; 

This keep returning false

Boolean Matched = AAA + BBB * X == TTT;
Long Result = AAA + BBB * X;
System.out.println(X.toString()+" Matched "+Matched.toString()+" Result "+Result.toString());

Solution

  • It's not completely clear what you are looking for, but note that java long arithmetic is effectively done mod 264. You can investigate modular inverses and the extended euclidean algorithm yourself, as well as how java handles integer overflow. The BigInteger class makes doing these experiments relatively easily, as this example shows.

    public class Main {
        static long AAA = 42L;
        static long BBB = -37L;
        static long TTT = 17206538691L;
    
        private static long solve() {
            // compute x = inverse(BBB, 1<<64) * (TTT - AAA)
    
            BigInteger two_64 = BigInteger.ONE.shiftLeft(64);
            BigInteger BBB_inverse = BigInteger.valueOf(BBB).modInverse(two_64);
            return BBB_inverse.multiply(BigInteger.valueOf(TTT - AAA)).longValue();
        }
    
        public static void main(String[] args) {
            System.out.println(solve());
        }
    }
    

    which shows that the answer is -5982727808154625893L.

    This only works if BBB is an odd integer.