+ 1

How does odd and even output work in this code?

int n = new Scanner(System.in).nextInt(); System.out.printf(new String[]{"even","odd"}[n-n/2*2]);

1st Oct 2019, 3:45 AM
Juan Debenedetti
Juan Debenedetti - avatar
2 ответов
+ 1
Well it indexes the array {"even", "odd"} using a formula that evaluates to 0 if even, and 1 if odd. Let's see what is happening here, the formula happens to be n-n/2*2, but wait! Couldn't I simplify that to 0? The answer is no because n is an int, so n/2 is an integer division. An integer division results in the quotient of that division: eg: 5/2=2 (even though it wouldve been 2.5 if it was a floating point division) if n is an even number, the result of the integer division wouldve been the same as the floating point division (no remainder), but if n is an odd number, the 0.5 from the result is "lost". Now there is a way to tell the difference between an even an odd number! When we multiply this result by 2 n/2*2, if n is an even number then n/2*2==n, but if n is an odd number then n/2*2==n-1. We can rearrange it so that 0 or 1 is on one side: n-n/2*2==0 and n-n/2*2==1. Notice the n-n/2*2 repeated? This is the formula we need to get 0 or 1 to index the array we made based on whether n is even or odd.
1st Oct 2019, 4:11 AM
jtrh
jtrh - avatar
+ 1
A simpler way is to index the array using by getting the remainder of that division, which is essentially what n-n/2*2 does: n%2.
1st Oct 2019, 4:14 AM
jtrh
jtrh - avatar