I have a snippet from my code where a statement that seems like it should evaluate to "false" actually returns true.
long composite = -1L;
ArrayList<Long> primes = new ArrayList<Long>();
ArrayList<Long> squares = new ArrayList<Long>();
squares.add(1L);
primes.add(2L);
primes.add(3L);
for (long i = 4; composite == -1L; i++) {
double sqrt_max = Math.sqrt((double) i);
if (sqrt_max == (int) sqrt_max) squares.add(i);
if (i % 2 == 0) continue;
boolean prime = true;
for (int j = 0; primes.get(j) <= sqrt_max; j++) {
if (i % primes.get(j) == 0) {// number is not prime
prime = false;
break;
}
}
if (prime) { // number is prime
primes.add(i);
}
else {
boolean conjTrue = false;
for (Long l : primes) {
ListIterator<Long> it = squares.listIterator(squares.size() - 1);
while (it.hasPrevious()) {
long m = it.previous();
if (l + 2L * m == i) {
conjTrue = true;
break;
}
else if (l + 2L * m < i) break;
}
if (conjTrue) break;
}
if (!conjTrue) composite = i;
}
}
System.out.println("\nAnswer: " + composite);
As it stands, this code works fine (I finished debugging), but I found a problem that I could not explain and I wanted to learn.
The relational statement else if (l + 2L * m < i), when the variables evaluate to (19 + 2 * 9 < 27) -> (38 < 27) (obviously false) would evaluate to true if the code was instead else if (l + 2 * m < i). Note the 2L is replaced with a 2 (int). I even used a print statement directly after the else if to test the value of the boolean l + 2 * m < i and would get true.
Something about being within the else if conditional parentheses and the implicit typecast caused the relation to erroneously evaluate to true. Within other contexts it would compute correctly. What could cause this issue?
To simplify your question,
It seems that you are suggesting that
would print true.
output