Guys, such a trouble. I do not understand what is the error. I need to, in the loop, at the output 2, the numbers are odd, but for some reason, the loop ends when one number is even, it closes the second number. I tried both &&, and &, I understand their difference, but it does not help. Please do not show off, and clearly explain what I'm doing wrong here. With me cookies, my mother cooks them delicious

class Test{ public static void main(String[] args){ int i,j; do { i = (int) (Math.random()*10); j = (int) (Math.random()*10); } while ((i % 2) != 0 & (j % 2) != 0); System.out.println("i = " + i + " j = " + j); } } 

The conclusion is (a few examples)

 i = 3 j = 2 i = 6 j = 7 i = 4 j = 3 
  • at the output 2 numbers were odd: while ((i % 2) == 0 || (j % 2) == 0) - Igor
  • (i % 2) == 0 - parity, (i % 2) > 0 - oddness. - Rootware
  • Why get two random values ​​in pairs? (so that they are odd and generated in a row) - dgzargo
  • @dgzargo, do you mean that it is more efficient to generate numbers separately? - aiDOSx
  • one
    @aiDOSx a=2n+1 - the formula of odd numbers (if in the example, the random in the example is random in practice); but if you generate them separately - the probability of catching the two odd ones is higher, the method is faster - dgzargo

2 answers 2

An error in the algorithm. It is necessary to do a cycle from the reverse, i.e. while at least one number is even:

  do { i = (int) (Math.random()*10); j = (int) (Math.random()*10); } while ((i % 2) == 0 || (j % 2) == 0); 
  • But, I understood my mistake, the algorithm worked until both numbers became odd and stopped working when one of them stopped being odd. Thanks for the answer! - aiDOSx

I would try while (!(( ((i % 2) != 0) && ((j % 2) != 0) )) but I recommend using the formula

 int i = ((int) (Math.random()*10))*2+1; int j = ((int) (Math.random()*10))*2+1; 

here the numbers will be generated immediately odd
a = 2n + 1

  • "the numbers will be generated immediately odd" - for example, random returned 0.05 - Igor
  • @Igor is strange that I was wrong. This is a very simple operation. corrected, it seems - dgzargo