The task is as follows: Output the following even number after the current one. The numbers are integers.

Example: Input: 5, Output: 6. or Input: 6, Output: 8.

The problem is that you can not use an if construct or cycles. With a quick reflection and search for similar solutions in the search engine did not find anything useful. Tell me please, what algorithms are there?

Java language.

    4 answers 4

    If there are no severe restrictions on the size of the source data, then something like that would fit

    x = x+2 - (x&1); 

    or

     x = (x+2)&(-2) 
    • Thanks, it helped. And how does the logic of the expression "x = (x + 2) & (- 2)" work? - Makis
    • and whether it is correct to do bit operations with negative from the point of view of the standard? I would rather write not (-2) but (~ 1) ... - pavel
    • @pavel, this is Java, not pluses. - Qwertiy
    • one
      @Makis, the number -2 is the negation of 1. That is, all bits except the low one are equal to 1. By nulling the low bit, we make the number even. - Zealint
    • one
      @pavel so it seems the other way around, this is the only option that works for negative ones (the rest give out 2 more) - zRrr

    The variant with the remainder of the division.

      X+2-X%2 

    Example:

     class Main { public static void main(String[] args) { for(int i = 1; i <= 100; i++) { System.out.println(i+" " + a(i)); } } public static int a(int x) {return x+2-x%2;} } 
    • Thank you, but this option does not work. - Makis
    • @Makis did something wrong. class Main {public static void main (String [] args) {for (int i = 1; i <= 100; i ++) {System.out.println (i + "" + a (i)); }} public static int a (int x) {return x + 2-x% 2;}} - GreyGoblin
    • You are right, I used "x = X + 2-X% 2" instead of "a = X + 2-X% 2". This option also works. Thank. - Makis
    • @Makis keep in mind that with negative numbers does not work correctly. The formulation of the problem does not indicate that the numbers will be only positive. - GreyGoblin 2:17 pm

    Another option for the collection:

     x=(x/2+1)*2 
    • Your option does not work correctly for negative numbers. And my way too. - GreyGoblin pm
    • Yes, indeed, did not take into account that they can be negative. - Yaant
     public class Even { public static void main(String[] args) { int x = -4; System.out.println("x=" + x + ", next even " + (x + 2 - Math.abs(x)%2)); } } x=-5, next even -4 x=-4, next even -2 x=-3, next even -2 x=-2, next even 0 x=-1, next even 0 x=0, next even 2 x=1, next even 2 x=2, next even 4 x=3, next even 4 x=4, next even 6 x=5, next even 6 
    • Thank. A good option - Makis