ihya ainun Fikri
ihya ainun Fikri

Reputation: 65

Why can I get the process of my while condition with biginteger variable

I want to make my while loop work when the condition is not equal to one. I want to make while (biginteger a is not one), but in my code it is not working

while (hasil.compareTo(BigInteger.valueOf(1)) == 0) {
    hasil = d.multiply(BigInteger.valueOf(b)).remainder(BigInteger.valueOf(m));

    out.println(d + " x " + b + "mod " + m + "=" + hasil);

    d = d.add(BigInteger.ONE);            
}

Upvotes: 1

Views: 54

Answers (3)

Kaan
Kaan

Reputation: 5784

The logic inside the while condition is wrong, and tricky enough that it wasn't easy to spot. Instead of doing a single combined statement in the while condition, you could check something in the statement body, and use break to exit the loop.

Here's an example which uses a few statements to make it clear what the comparison is doing, and clear when the loop will exit.

while (true) {

    // do other things

    int result = hasil.compareTo(BigInteger.valueOf(1));
    boolean valuesAreEqual = (result == 0);
    if (valuesAreEqual) {
        break;
    }
}

Upvotes: 0

user728785
user728785

Reputation: 542

Just modify the condition

while (hasil.compareTo(BigInteger.valueOf(1)) != 0) 

As you are looking for the value not to be equal to one, as mentioned by @khelwood

Upvotes: 0

Jacob G.
Jacob G.

Reputation: 29710

while (hasil.compareTo(BigInteger.valueOf(1)) == 0)

The above snippet is equivalent to the following:

while (BigInteger.ONE.equals(hasil))  // hasil == 1

To check if hasil is not equal to BigInteger.ONE, you must negate the condition:

while (!BigInteger.ONE.equals(hasil)) // hasil != 1

Upvotes: 2

Related Questions