What's the syntax for mod in javamath in java - what does “ %” do?Im having trouble figuring out how to get the program to tell me if the word length is even or oddDetermining even/odd numbers (integers)?What are the best Java example sites?reading string each number c#Java modular inverseWhat does the percentage symbol (%) mean?What is the % operator in java?Why cant I assign a remainder to a new variable??? JAVAHow to compare last digit of number w/ last digit of another number?Is Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?What is the difference between public, protected, package-private and private in Java?How do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?What's the simplest way to print a Java array?How do I convert a String to an int in Java?Creating a memory leak with JavaWhat's the difference between @Component, @Repository & @Service annotations in Spring?
Air travel with refrigerated insulin
Should I be concerned about student access to a test bank?
A seasonal riddle
Is there a distance limit for minecart tracks?
How do I prevent inappropriate ads from appearing in my game?
Why is implicit conversion not ambiguous for non-primitive types?
Derivative of an interpolated function
Writing in a Christian voice
Error in master's thesis, I do not know what to do
How to test the sharpness of a knife?
Why can't I get pgrep output right to variable on bash script?
What do the positive and negative (+/-) transmit and receive pins mean on Ethernet cables?
categorizing a variable turns it from insignificant to significant
Do I have to take mana from my deck or hand when tapping this card?
How to join two vertical cells in latex?
Why does the Persian emissary display a string of crowned skulls?
What is the probability that the nth card becomes the top card after shuffling a certain way?
How do you justify more code being written by following clean code practices?
Has the laser at Magurele, Romania reached a tenth of the Sun's power?
PTIJ: Which Dr. Seuss books should one obtain?
How would a solely written language work mechanically
What should be the ideal length of sentences in a blog post for ease of reading?
Is there any common country to visit for persons holding UK and Schengen visas?
How to preserve electronics (computers, ipads, phones) for hundreds of years?
What's the syntax for mod in java
math in java - what does “ %” do?Im having trouble figuring out how to get the program to tell me if the word length is even or oddDetermining even/odd numbers (integers)?What are the best Java example sites?reading string each number c#Java modular inverseWhat does the percentage symbol (%) mean?What is the % operator in java?Why cant I assign a remainder to a new variable??? JAVAHow to compare last digit of number w/ last digit of another number?Is Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?What is the difference between public, protected, package-private and private in Java?How do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?What's the simplest way to print a Java array?How do I convert a String to an int in Java?Creating a memory leak with JavaWhat's the difference between @Component, @Repository & @Service annotations in Spring?
As an example in pseudocode:
if ((a mod 2) == 0)
isEven = true;
else
isEven = false;
java modulo
add a comment |
As an example in pseudocode:
if ((a mod 2) == 0)
isEven = true;
else
isEven = false;
java modulo
add a comment |
As an example in pseudocode:
if ((a mod 2) == 0)
isEven = true;
else
isEven = false;
java modulo
As an example in pseudocode:
if ((a mod 2) == 0)
isEven = true;
else
isEven = false;
java modulo
java modulo
edited Nov 17 '15 at 10:18
sschuberth
17.4k465107
17.4k465107
asked Sep 18 '08 at 5:17
BobBob
1,121286
1,121286
add a comment |
add a comment |
15 Answers
15
active
oldest
votes
For non-negative integers, you can use the remainder operator %
. For your exact example:
if ((a % 2) == 0)
isEven = true;
else
isEven = false;
This can be simplified to a one-liner:
isEven = (a % 2) == 0;
75
The if/else is unnecessary, just use isEven = (a%2)==0,
– Steve Kuo
Jul 28 '10 at 15:12
56
Careful with the terms mod and modular because n (mod m) IS ALWAYS >= 0 but not n % m. n % m is in the range > -m and < m. Although Java has a remainder operator for int and long types, it has no modulus function or operator. I.e., -12 % 10 = -2 whereas -12 mod 10 = 8. If % operator returns a negative value for n % m, then (n % m) + m will give you n mod m. BigInteger provides functions for both and the specifications for them explain the difference quite well. Also, careful with zero. In mathematics, whilst zero is an even number it is NOT positive or negative.
– Jim
Aug 24 '12 at 22:36
4
@nl-x Probably because it's better to be explicit about precedence than leave it to convention. I for one did not know that%
is evaluated before==
before I looked it up, so it would be unclear whether the expression is equivalent to(a%2)==0
ora%(2==0)
. I guess it is less important in java where a boolean is not the same as an integer
– Matthew Sainsbury
Jun 6 '14 at 12:13
7
This isn't the modulus operator - it's the remainder operator. Please correct the post!
– Kieren Johnstone
Jul 17 '15 at 6:56
2
boolean even = ((a & 1) == 0). Much easier.
– mdev
Mar 11 '18 at 3:36
|
show 2 more comments
Here is the representation of your pseudo-code in minimal Java code;
boolean isEven = a % 2 == 0;
I'll now break it down into its components. The modulus operator in Java is the percent character (%). Therefore taking an int % int returns another int. The double equals (==) operator is used to compare values, such as a pair of ints and returns a boolean. This is then assigned to the boolean variable 'isEven'. Based on operator precedence the modulus will be evaluated before the comparison.
12
minimal would be without the brackets ;)
– pstanton
Sep 28 '10 at 1:29
2
It's a remainder operator, not a modulus operator.
– user207421
Mar 30 '16 at 1:51
add a comment |
Since everyone else already gave the answer, I'll add a bit of additional context. % the "modulus" operator is actually performing the remainder operation. The difference between mod and rem is subtle, but important.
(-1 mod 2) would normally give 1. More specifically given two integers, X and Y, the operation (X mod Y) tends to return a value in the range [0, Y). Said differently, the modulus of X and Y is always greater than or equal to zero, and less than Y.
Performing the same operation with the "%" or rem operator maintains the sign of the X value. If X is negative you get a result in the range (-Y, 0]. If X is positive you get a result in the range [0, Y).
Often this subtle distinction doesn't matter. Going back to your code question, though, there are multiple ways of solving for "evenness".
The first approach is good for beginners, because it is especially verbose.
// Option 1: Clearest way for beginners
boolean isEven;
if ((a % 2) == 0)
isEven = true
else
isEven = false
The second approach takes better advantage of the language, and leads to more succinct code. (Don't forget that the == operator returns a boolean.)
// Option 2: Clear, succinct, code
boolean isEven = ((a % 2) == 0);
The third approach is here for completeness, and uses the ternary operator. Although the ternary operator is often very useful, in this case I consider the second approach superior.
// Option 3: Ternary operator
boolean isEven = ((a % 2) == 0) ? true : false;
The fourth and final approach is to use knowledge of the binary representation of integers. If the least significant bit is 0 then the number is even. This can be checked using the bitwise-and operator (&). While this approach is the fastest (you are doing simple bit masking instead of division), it is perhaps a little advanced/complicated for a beginner.
// Option 4: Bitwise-and
boolean isEven = ((a & 1) == 0);
Here I used the bitwise-and operator, and represented it in the succinct form shown in option 2. Rewriting it in Option 1's form (and alternatively Option 3's) is left as an exercise to the reader. ;)
Hope that helps.
4
Taking Option 4 to the extreme, boolean isEven = !(a & 1), returning the opposite of whether a is an odd number where a & 1 == 1 (true). Of course, that's the sort of coder trick that makes code incomprehensible. ;)
– Tickled Pink
Aug 23 '12 at 21:38
Thank you Rob. This confusion causes enormous difficulties in explaining to programmers how to implement algorithms with mathematical properties from modular arithmetic. Remainder is NOT modulus but one can quickly derive a modulus from remainders.
– Jim
Aug 24 '12 at 22:12
add a comment |
To get Java's % (REM) operation to work like MOD for negative X and positive Y values, you can use this method:
private int mod(int x, int y)
int result = x % y;
if (result < 0)
result += y;
return result;
or with the ternary operator (shorter, but not possible or less efficient in some situations):
private int mod(int x, int y)
int result = x % y;
return result < 0? result + y : result;
add a comment |
While it's possible to do a proper modulo by checking whether the value is negative and correct it if it is (the way many have suggested), there is a more compact solution.
(a % b + b) % b
This will first do the modulo, limiting the value to the -b -> +b range and then add b in order to ensure that the value is positive, letting the next modulo limit it to the 0 -> b range.
Note: If b is negative, the result will also be negative
This can overflow when a and b are both large numbers, so it is not a correct solution.
– Trixie Wolf
Sep 12 '18 at 15:49
add a comment |
Java actually has no modulo operator the way C does. % in Java is a remainder operator. On positive integers, it works exactly like modulo, but it works differently on negative integers and, unlike modulo, can work with floating point numbers as well. Still, it's rare to use % on anything but positive integers, so if you want to call it a modulo, then feel free!
add a comment |
The code runs much faster without using modulo:
public boolean isEven(int a)
return ( (a & 1) == 0 );
public boolean isOdd(int a)
return ( (a & 1) == 1 );
4
Premature optimization much?
– Lluis Martinez
Sep 25 '12 at 10:07
3
This looks much cleaner than the accepted answer. This has nothing to do with premature optimization. Its simply better, -- if it works.
– AlexWien
Jul 15 '13 at 19:39
3
@LluisMartinez This is one of the most misquoted sayings in computing. The full quotation is "Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.". Which actually means something quite different.
– user207421
Nov 17 '15 at 10:35
3
@EJP You're probably right. I did a test (loop with 1 million iterations) took 4000 nanoseconds with modulo, 2500 nanoseconds with logical and.
– Lluis Martinez
Nov 18 '15 at 0:43
add a comment |
if (a % 2 == 0)
else
add a comment |
you should examine the specification before using 'remainder' operator % :
http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.17.3
// bad enough implementation of isEven method, for fun. so any worse?
boolean isEven(int num)
num %= 10;
if(num == 1)
return false;
else if(num == 0)
return true;
else
return isEven(num + 2);
isEven = isEven(a);
add a comment |
Also, mod can be used like this:
int a = 7;
b = a % 2;
b
would equal 1. Because 7 % 2 = 1
.
it is probably a mistake to use compound operators in an example for beginners, and without output.
– Stu Thompson
Sep 18 '08 at 6:48
This is probably true.
– jjnguy
Sep 18 '08 at 15:04
add a comment |
The remainder operator in Java is %
and the modulo operator can be expressed as
public int mod(int i, int j)
int rem = i % j;
if (j < 0 && rem > 0)
return rem + j;
if (j > 0 && rem < 0)
return rem + j;
return rem;
add a comment |
The modulo operator is % (percent sign). To test for evenness or generally do modulo for a power of 2, you can also use & (the and operator) like isEven = !( a & 1 ).
add a comment |
Another way is:
boolean isEven = false;
if((a % 2) == 0)
isEven = true;
But easiest way is still:
boolean isEven = (a % 2) == 0;
Like @Steve Kuo said.
add a comment |
In Java it is the %
operator:
15.17.3. Remainder Operator %
Note that there is also floorMod
in the java.lang.Math
class which will give a different result from %
for arguments with different signs:
public static int floorMod(int x, int y)
add a comment |
An alternative to the code from @Cody:
Using the modulus operator:
bool isEven = (a % 2) == 0;
I think this is marginally better code than writing if/else, because there is less duplication & unused flexibility. It does require a bit more brain power to examine, but the good naming of isEven
compensates.
2
It's a remainder operator, not a modulus operator.
– user207421
Mar 30 '16 at 1:53
@EJP ok. Then what is the modulus operator?
– TheRealChx101
Jul 19 '18 at 22:29
add a comment |
protected by bummi May 12 '14 at 13:35
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
15 Answers
15
active
oldest
votes
15 Answers
15
active
oldest
votes
active
oldest
votes
active
oldest
votes
For non-negative integers, you can use the remainder operator %
. For your exact example:
if ((a % 2) == 0)
isEven = true;
else
isEven = false;
This can be simplified to a one-liner:
isEven = (a % 2) == 0;
75
The if/else is unnecessary, just use isEven = (a%2)==0,
– Steve Kuo
Jul 28 '10 at 15:12
56
Careful with the terms mod and modular because n (mod m) IS ALWAYS >= 0 but not n % m. n % m is in the range > -m and < m. Although Java has a remainder operator for int and long types, it has no modulus function or operator. I.e., -12 % 10 = -2 whereas -12 mod 10 = 8. If % operator returns a negative value for n % m, then (n % m) + m will give you n mod m. BigInteger provides functions for both and the specifications for them explain the difference quite well. Also, careful with zero. In mathematics, whilst zero is an even number it is NOT positive or negative.
– Jim
Aug 24 '12 at 22:36
4
@nl-x Probably because it's better to be explicit about precedence than leave it to convention. I for one did not know that%
is evaluated before==
before I looked it up, so it would be unclear whether the expression is equivalent to(a%2)==0
ora%(2==0)
. I guess it is less important in java where a boolean is not the same as an integer
– Matthew Sainsbury
Jun 6 '14 at 12:13
7
This isn't the modulus operator - it's the remainder operator. Please correct the post!
– Kieren Johnstone
Jul 17 '15 at 6:56
2
boolean even = ((a & 1) == 0). Much easier.
– mdev
Mar 11 '18 at 3:36
|
show 2 more comments
For non-negative integers, you can use the remainder operator %
. For your exact example:
if ((a % 2) == 0)
isEven = true;
else
isEven = false;
This can be simplified to a one-liner:
isEven = (a % 2) == 0;
75
The if/else is unnecessary, just use isEven = (a%2)==0,
– Steve Kuo
Jul 28 '10 at 15:12
56
Careful with the terms mod and modular because n (mod m) IS ALWAYS >= 0 but not n % m. n % m is in the range > -m and < m. Although Java has a remainder operator for int and long types, it has no modulus function or operator. I.e., -12 % 10 = -2 whereas -12 mod 10 = 8. If % operator returns a negative value for n % m, then (n % m) + m will give you n mod m. BigInteger provides functions for both and the specifications for them explain the difference quite well. Also, careful with zero. In mathematics, whilst zero is an even number it is NOT positive or negative.
– Jim
Aug 24 '12 at 22:36
4
@nl-x Probably because it's better to be explicit about precedence than leave it to convention. I for one did not know that%
is evaluated before==
before I looked it up, so it would be unclear whether the expression is equivalent to(a%2)==0
ora%(2==0)
. I guess it is less important in java where a boolean is not the same as an integer
– Matthew Sainsbury
Jun 6 '14 at 12:13
7
This isn't the modulus operator - it's the remainder operator. Please correct the post!
– Kieren Johnstone
Jul 17 '15 at 6:56
2
boolean even = ((a & 1) == 0). Much easier.
– mdev
Mar 11 '18 at 3:36
|
show 2 more comments
For non-negative integers, you can use the remainder operator %
. For your exact example:
if ((a % 2) == 0)
isEven = true;
else
isEven = false;
This can be simplified to a one-liner:
isEven = (a % 2) == 0;
For non-negative integers, you can use the remainder operator %
. For your exact example:
if ((a % 2) == 0)
isEven = true;
else
isEven = false;
This can be simplified to a one-liner:
isEven = (a % 2) == 0;
edited Mar 30 '16 at 0:49
Community♦
11
11
answered Sep 18 '08 at 5:18
Cody HatchCody Hatch
7,17652536
7,17652536
75
The if/else is unnecessary, just use isEven = (a%2)==0,
– Steve Kuo
Jul 28 '10 at 15:12
56
Careful with the terms mod and modular because n (mod m) IS ALWAYS >= 0 but not n % m. n % m is in the range > -m and < m. Although Java has a remainder operator for int and long types, it has no modulus function or operator. I.e., -12 % 10 = -2 whereas -12 mod 10 = 8. If % operator returns a negative value for n % m, then (n % m) + m will give you n mod m. BigInteger provides functions for both and the specifications for them explain the difference quite well. Also, careful with zero. In mathematics, whilst zero is an even number it is NOT positive or negative.
– Jim
Aug 24 '12 at 22:36
4
@nl-x Probably because it's better to be explicit about precedence than leave it to convention. I for one did not know that%
is evaluated before==
before I looked it up, so it would be unclear whether the expression is equivalent to(a%2)==0
ora%(2==0)
. I guess it is less important in java where a boolean is not the same as an integer
– Matthew Sainsbury
Jun 6 '14 at 12:13
7
This isn't the modulus operator - it's the remainder operator. Please correct the post!
– Kieren Johnstone
Jul 17 '15 at 6:56
2
boolean even = ((a & 1) == 0). Much easier.
– mdev
Mar 11 '18 at 3:36
|
show 2 more comments
75
The if/else is unnecessary, just use isEven = (a%2)==0,
– Steve Kuo
Jul 28 '10 at 15:12
56
Careful with the terms mod and modular because n (mod m) IS ALWAYS >= 0 but not n % m. n % m is in the range > -m and < m. Although Java has a remainder operator for int and long types, it has no modulus function or operator. I.e., -12 % 10 = -2 whereas -12 mod 10 = 8. If % operator returns a negative value for n % m, then (n % m) + m will give you n mod m. BigInteger provides functions for both and the specifications for them explain the difference quite well. Also, careful with zero. In mathematics, whilst zero is an even number it is NOT positive or negative.
– Jim
Aug 24 '12 at 22:36
4
@nl-x Probably because it's better to be explicit about precedence than leave it to convention. I for one did not know that%
is evaluated before==
before I looked it up, so it would be unclear whether the expression is equivalent to(a%2)==0
ora%(2==0)
. I guess it is less important in java where a boolean is not the same as an integer
– Matthew Sainsbury
Jun 6 '14 at 12:13
7
This isn't the modulus operator - it's the remainder operator. Please correct the post!
– Kieren Johnstone
Jul 17 '15 at 6:56
2
boolean even = ((a & 1) == 0). Much easier.
– mdev
Mar 11 '18 at 3:36
75
75
The if/else is unnecessary, just use isEven = (a%2)==0,
– Steve Kuo
Jul 28 '10 at 15:12
The if/else is unnecessary, just use isEven = (a%2)==0,
– Steve Kuo
Jul 28 '10 at 15:12
56
56
Careful with the terms mod and modular because n (mod m) IS ALWAYS >= 0 but not n % m. n % m is in the range > -m and < m. Although Java has a remainder operator for int and long types, it has no modulus function or operator. I.e., -12 % 10 = -2 whereas -12 mod 10 = 8. If % operator returns a negative value for n % m, then (n % m) + m will give you n mod m. BigInteger provides functions for both and the specifications for them explain the difference quite well. Also, careful with zero. In mathematics, whilst zero is an even number it is NOT positive or negative.
– Jim
Aug 24 '12 at 22:36
Careful with the terms mod and modular because n (mod m) IS ALWAYS >= 0 but not n % m. n % m is in the range > -m and < m. Although Java has a remainder operator for int and long types, it has no modulus function or operator. I.e., -12 % 10 = -2 whereas -12 mod 10 = 8. If % operator returns a negative value for n % m, then (n % m) + m will give you n mod m. BigInteger provides functions for both and the specifications for them explain the difference quite well. Also, careful with zero. In mathematics, whilst zero is an even number it is NOT positive or negative.
– Jim
Aug 24 '12 at 22:36
4
4
@nl-x Probably because it's better to be explicit about precedence than leave it to convention. I for one did not know that
%
is evaluated before ==
before I looked it up, so it would be unclear whether the expression is equivalent to (a%2)==0
or a%(2==0)
. I guess it is less important in java where a boolean is not the same as an integer– Matthew Sainsbury
Jun 6 '14 at 12:13
@nl-x Probably because it's better to be explicit about precedence than leave it to convention. I for one did not know that
%
is evaluated before ==
before I looked it up, so it would be unclear whether the expression is equivalent to (a%2)==0
or a%(2==0)
. I guess it is less important in java where a boolean is not the same as an integer– Matthew Sainsbury
Jun 6 '14 at 12:13
7
7
This isn't the modulus operator - it's the remainder operator. Please correct the post!
– Kieren Johnstone
Jul 17 '15 at 6:56
This isn't the modulus operator - it's the remainder operator. Please correct the post!
– Kieren Johnstone
Jul 17 '15 at 6:56
2
2
boolean even = ((a & 1) == 0). Much easier.
– mdev
Mar 11 '18 at 3:36
boolean even = ((a & 1) == 0). Much easier.
– mdev
Mar 11 '18 at 3:36
|
show 2 more comments
Here is the representation of your pseudo-code in minimal Java code;
boolean isEven = a % 2 == 0;
I'll now break it down into its components. The modulus operator in Java is the percent character (%). Therefore taking an int % int returns another int. The double equals (==) operator is used to compare values, such as a pair of ints and returns a boolean. This is then assigned to the boolean variable 'isEven'. Based on operator precedence the modulus will be evaluated before the comparison.
12
minimal would be without the brackets ;)
– pstanton
Sep 28 '10 at 1:29
2
It's a remainder operator, not a modulus operator.
– user207421
Mar 30 '16 at 1:51
add a comment |
Here is the representation of your pseudo-code in minimal Java code;
boolean isEven = a % 2 == 0;
I'll now break it down into its components. The modulus operator in Java is the percent character (%). Therefore taking an int % int returns another int. The double equals (==) operator is used to compare values, such as a pair of ints and returns a boolean. This is then assigned to the boolean variable 'isEven'. Based on operator precedence the modulus will be evaluated before the comparison.
12
minimal would be without the brackets ;)
– pstanton
Sep 28 '10 at 1:29
2
It's a remainder operator, not a modulus operator.
– user207421
Mar 30 '16 at 1:51
add a comment |
Here is the representation of your pseudo-code in minimal Java code;
boolean isEven = a % 2 == 0;
I'll now break it down into its components. The modulus operator in Java is the percent character (%). Therefore taking an int % int returns another int. The double equals (==) operator is used to compare values, such as a pair of ints and returns a boolean. This is then assigned to the boolean variable 'isEven'. Based on operator precedence the modulus will be evaluated before the comparison.
Here is the representation of your pseudo-code in minimal Java code;
boolean isEven = a % 2 == 0;
I'll now break it down into its components. The modulus operator in Java is the percent character (%). Therefore taking an int % int returns another int. The double equals (==) operator is used to compare values, such as a pair of ints and returns a boolean. This is then assigned to the boolean variable 'isEven'. Based on operator precedence the modulus will be evaluated before the comparison.
edited Sep 18 '15 at 11:25
Clashsoft
5,96143155
5,96143155
answered Sep 18 '08 at 5:18
martinatimemartinatime
2,22711420
2,22711420
12
minimal would be without the brackets ;)
– pstanton
Sep 28 '10 at 1:29
2
It's a remainder operator, not a modulus operator.
– user207421
Mar 30 '16 at 1:51
add a comment |
12
minimal would be without the brackets ;)
– pstanton
Sep 28 '10 at 1:29
2
It's a remainder operator, not a modulus operator.
– user207421
Mar 30 '16 at 1:51
12
12
minimal would be without the brackets ;)
– pstanton
Sep 28 '10 at 1:29
minimal would be without the brackets ;)
– pstanton
Sep 28 '10 at 1:29
2
2
It's a remainder operator, not a modulus operator.
– user207421
Mar 30 '16 at 1:51
It's a remainder operator, not a modulus operator.
– user207421
Mar 30 '16 at 1:51
add a comment |
Since everyone else already gave the answer, I'll add a bit of additional context. % the "modulus" operator is actually performing the remainder operation. The difference between mod and rem is subtle, but important.
(-1 mod 2) would normally give 1. More specifically given two integers, X and Y, the operation (X mod Y) tends to return a value in the range [0, Y). Said differently, the modulus of X and Y is always greater than or equal to zero, and less than Y.
Performing the same operation with the "%" or rem operator maintains the sign of the X value. If X is negative you get a result in the range (-Y, 0]. If X is positive you get a result in the range [0, Y).
Often this subtle distinction doesn't matter. Going back to your code question, though, there are multiple ways of solving for "evenness".
The first approach is good for beginners, because it is especially verbose.
// Option 1: Clearest way for beginners
boolean isEven;
if ((a % 2) == 0)
isEven = true
else
isEven = false
The second approach takes better advantage of the language, and leads to more succinct code. (Don't forget that the == operator returns a boolean.)
// Option 2: Clear, succinct, code
boolean isEven = ((a % 2) == 0);
The third approach is here for completeness, and uses the ternary operator. Although the ternary operator is often very useful, in this case I consider the second approach superior.
// Option 3: Ternary operator
boolean isEven = ((a % 2) == 0) ? true : false;
The fourth and final approach is to use knowledge of the binary representation of integers. If the least significant bit is 0 then the number is even. This can be checked using the bitwise-and operator (&). While this approach is the fastest (you are doing simple bit masking instead of division), it is perhaps a little advanced/complicated for a beginner.
// Option 4: Bitwise-and
boolean isEven = ((a & 1) == 0);
Here I used the bitwise-and operator, and represented it in the succinct form shown in option 2. Rewriting it in Option 1's form (and alternatively Option 3's) is left as an exercise to the reader. ;)
Hope that helps.
4
Taking Option 4 to the extreme, boolean isEven = !(a & 1), returning the opposite of whether a is an odd number where a & 1 == 1 (true). Of course, that's the sort of coder trick that makes code incomprehensible. ;)
– Tickled Pink
Aug 23 '12 at 21:38
Thank you Rob. This confusion causes enormous difficulties in explaining to programmers how to implement algorithms with mathematical properties from modular arithmetic. Remainder is NOT modulus but one can quickly derive a modulus from remainders.
– Jim
Aug 24 '12 at 22:12
add a comment |
Since everyone else already gave the answer, I'll add a bit of additional context. % the "modulus" operator is actually performing the remainder operation. The difference between mod and rem is subtle, but important.
(-1 mod 2) would normally give 1. More specifically given two integers, X and Y, the operation (X mod Y) tends to return a value in the range [0, Y). Said differently, the modulus of X and Y is always greater than or equal to zero, and less than Y.
Performing the same operation with the "%" or rem operator maintains the sign of the X value. If X is negative you get a result in the range (-Y, 0]. If X is positive you get a result in the range [0, Y).
Often this subtle distinction doesn't matter. Going back to your code question, though, there are multiple ways of solving for "evenness".
The first approach is good for beginners, because it is especially verbose.
// Option 1: Clearest way for beginners
boolean isEven;
if ((a % 2) == 0)
isEven = true
else
isEven = false
The second approach takes better advantage of the language, and leads to more succinct code. (Don't forget that the == operator returns a boolean.)
// Option 2: Clear, succinct, code
boolean isEven = ((a % 2) == 0);
The third approach is here for completeness, and uses the ternary operator. Although the ternary operator is often very useful, in this case I consider the second approach superior.
// Option 3: Ternary operator
boolean isEven = ((a % 2) == 0) ? true : false;
The fourth and final approach is to use knowledge of the binary representation of integers. If the least significant bit is 0 then the number is even. This can be checked using the bitwise-and operator (&). While this approach is the fastest (you are doing simple bit masking instead of division), it is perhaps a little advanced/complicated for a beginner.
// Option 4: Bitwise-and
boolean isEven = ((a & 1) == 0);
Here I used the bitwise-and operator, and represented it in the succinct form shown in option 2. Rewriting it in Option 1's form (and alternatively Option 3's) is left as an exercise to the reader. ;)
Hope that helps.
4
Taking Option 4 to the extreme, boolean isEven = !(a & 1), returning the opposite of whether a is an odd number where a & 1 == 1 (true). Of course, that's the sort of coder trick that makes code incomprehensible. ;)
– Tickled Pink
Aug 23 '12 at 21:38
Thank you Rob. This confusion causes enormous difficulties in explaining to programmers how to implement algorithms with mathematical properties from modular arithmetic. Remainder is NOT modulus but one can quickly derive a modulus from remainders.
– Jim
Aug 24 '12 at 22:12
add a comment |
Since everyone else already gave the answer, I'll add a bit of additional context. % the "modulus" operator is actually performing the remainder operation. The difference between mod and rem is subtle, but important.
(-1 mod 2) would normally give 1. More specifically given two integers, X and Y, the operation (X mod Y) tends to return a value in the range [0, Y). Said differently, the modulus of X and Y is always greater than or equal to zero, and less than Y.
Performing the same operation with the "%" or rem operator maintains the sign of the X value. If X is negative you get a result in the range (-Y, 0]. If X is positive you get a result in the range [0, Y).
Often this subtle distinction doesn't matter. Going back to your code question, though, there are multiple ways of solving for "evenness".
The first approach is good for beginners, because it is especially verbose.
// Option 1: Clearest way for beginners
boolean isEven;
if ((a % 2) == 0)
isEven = true
else
isEven = false
The second approach takes better advantage of the language, and leads to more succinct code. (Don't forget that the == operator returns a boolean.)
// Option 2: Clear, succinct, code
boolean isEven = ((a % 2) == 0);
The third approach is here for completeness, and uses the ternary operator. Although the ternary operator is often very useful, in this case I consider the second approach superior.
// Option 3: Ternary operator
boolean isEven = ((a % 2) == 0) ? true : false;
The fourth and final approach is to use knowledge of the binary representation of integers. If the least significant bit is 0 then the number is even. This can be checked using the bitwise-and operator (&). While this approach is the fastest (you are doing simple bit masking instead of division), it is perhaps a little advanced/complicated for a beginner.
// Option 4: Bitwise-and
boolean isEven = ((a & 1) == 0);
Here I used the bitwise-and operator, and represented it in the succinct form shown in option 2. Rewriting it in Option 1's form (and alternatively Option 3's) is left as an exercise to the reader. ;)
Hope that helps.
Since everyone else already gave the answer, I'll add a bit of additional context. % the "modulus" operator is actually performing the remainder operation. The difference between mod and rem is subtle, but important.
(-1 mod 2) would normally give 1. More specifically given two integers, X and Y, the operation (X mod Y) tends to return a value in the range [0, Y). Said differently, the modulus of X and Y is always greater than or equal to zero, and less than Y.
Performing the same operation with the "%" or rem operator maintains the sign of the X value. If X is negative you get a result in the range (-Y, 0]. If X is positive you get a result in the range [0, Y).
Often this subtle distinction doesn't matter. Going back to your code question, though, there are multiple ways of solving for "evenness".
The first approach is good for beginners, because it is especially verbose.
// Option 1: Clearest way for beginners
boolean isEven;
if ((a % 2) == 0)
isEven = true
else
isEven = false
The second approach takes better advantage of the language, and leads to more succinct code. (Don't forget that the == operator returns a boolean.)
// Option 2: Clear, succinct, code
boolean isEven = ((a % 2) == 0);
The third approach is here for completeness, and uses the ternary operator. Although the ternary operator is often very useful, in this case I consider the second approach superior.
// Option 3: Ternary operator
boolean isEven = ((a % 2) == 0) ? true : false;
The fourth and final approach is to use knowledge of the binary representation of integers. If the least significant bit is 0 then the number is even. This can be checked using the bitwise-and operator (&). While this approach is the fastest (you are doing simple bit masking instead of division), it is perhaps a little advanced/complicated for a beginner.
// Option 4: Bitwise-and
boolean isEven = ((a & 1) == 0);
Here I used the bitwise-and operator, and represented it in the succinct form shown in option 2. Rewriting it in Option 1's form (and alternatively Option 3's) is left as an exercise to the reader. ;)
Hope that helps.
answered Jan 15 '10 at 18:10
Rob RolnickRob Rolnick
6,58012316
6,58012316
4
Taking Option 4 to the extreme, boolean isEven = !(a & 1), returning the opposite of whether a is an odd number where a & 1 == 1 (true). Of course, that's the sort of coder trick that makes code incomprehensible. ;)
– Tickled Pink
Aug 23 '12 at 21:38
Thank you Rob. This confusion causes enormous difficulties in explaining to programmers how to implement algorithms with mathematical properties from modular arithmetic. Remainder is NOT modulus but one can quickly derive a modulus from remainders.
– Jim
Aug 24 '12 at 22:12
add a comment |
4
Taking Option 4 to the extreme, boolean isEven = !(a & 1), returning the opposite of whether a is an odd number where a & 1 == 1 (true). Of course, that's the sort of coder trick that makes code incomprehensible. ;)
– Tickled Pink
Aug 23 '12 at 21:38
Thank you Rob. This confusion causes enormous difficulties in explaining to programmers how to implement algorithms with mathematical properties from modular arithmetic. Remainder is NOT modulus but one can quickly derive a modulus from remainders.
– Jim
Aug 24 '12 at 22:12
4
4
Taking Option 4 to the extreme, boolean isEven = !(a & 1), returning the opposite of whether a is an odd number where a & 1 == 1 (true). Of course, that's the sort of coder trick that makes code incomprehensible. ;)
– Tickled Pink
Aug 23 '12 at 21:38
Taking Option 4 to the extreme, boolean isEven = !(a & 1), returning the opposite of whether a is an odd number where a & 1 == 1 (true). Of course, that's the sort of coder trick that makes code incomprehensible. ;)
– Tickled Pink
Aug 23 '12 at 21:38
Thank you Rob. This confusion causes enormous difficulties in explaining to programmers how to implement algorithms with mathematical properties from modular arithmetic. Remainder is NOT modulus but one can quickly derive a modulus from remainders.
– Jim
Aug 24 '12 at 22:12
Thank you Rob. This confusion causes enormous difficulties in explaining to programmers how to implement algorithms with mathematical properties from modular arithmetic. Remainder is NOT modulus but one can quickly derive a modulus from remainders.
– Jim
Aug 24 '12 at 22:12
add a comment |
To get Java's % (REM) operation to work like MOD for negative X and positive Y values, you can use this method:
private int mod(int x, int y)
int result = x % y;
if (result < 0)
result += y;
return result;
or with the ternary operator (shorter, but not possible or less efficient in some situations):
private int mod(int x, int y)
int result = x % y;
return result < 0? result + y : result;
add a comment |
To get Java's % (REM) operation to work like MOD for negative X and positive Y values, you can use this method:
private int mod(int x, int y)
int result = x % y;
if (result < 0)
result += y;
return result;
or with the ternary operator (shorter, but not possible or less efficient in some situations):
private int mod(int x, int y)
int result = x % y;
return result < 0? result + y : result;
add a comment |
To get Java's % (REM) operation to work like MOD for negative X and positive Y values, you can use this method:
private int mod(int x, int y)
int result = x % y;
if (result < 0)
result += y;
return result;
or with the ternary operator (shorter, but not possible or less efficient in some situations):
private int mod(int x, int y)
int result = x % y;
return result < 0? result + y : result;
To get Java's % (REM) operation to work like MOD for negative X and positive Y values, you can use this method:
private int mod(int x, int y)
int result = x % y;
if (result < 0)
result += y;
return result;
or with the ternary operator (shorter, but not possible or less efficient in some situations):
private int mod(int x, int y)
int result = x % y;
return result < 0? result + y : result;
answered Jan 31 '10 at 14:40
Zom-BZom-B
31132
31132
add a comment |
add a comment |
While it's possible to do a proper modulo by checking whether the value is negative and correct it if it is (the way many have suggested), there is a more compact solution.
(a % b + b) % b
This will first do the modulo, limiting the value to the -b -> +b range and then add b in order to ensure that the value is positive, letting the next modulo limit it to the 0 -> b range.
Note: If b is negative, the result will also be negative
This can overflow when a and b are both large numbers, so it is not a correct solution.
– Trixie Wolf
Sep 12 '18 at 15:49
add a comment |
While it's possible to do a proper modulo by checking whether the value is negative and correct it if it is (the way many have suggested), there is a more compact solution.
(a % b + b) % b
This will first do the modulo, limiting the value to the -b -> +b range and then add b in order to ensure that the value is positive, letting the next modulo limit it to the 0 -> b range.
Note: If b is negative, the result will also be negative
This can overflow when a and b are both large numbers, so it is not a correct solution.
– Trixie Wolf
Sep 12 '18 at 15:49
add a comment |
While it's possible to do a proper modulo by checking whether the value is negative and correct it if it is (the way many have suggested), there is a more compact solution.
(a % b + b) % b
This will first do the modulo, limiting the value to the -b -> +b range and then add b in order to ensure that the value is positive, letting the next modulo limit it to the 0 -> b range.
Note: If b is negative, the result will also be negative
While it's possible to do a proper modulo by checking whether the value is negative and correct it if it is (the way many have suggested), there is a more compact solution.
(a % b + b) % b
This will first do the modulo, limiting the value to the -b -> +b range and then add b in order to ensure that the value is positive, letting the next modulo limit it to the 0 -> b range.
Note: If b is negative, the result will also be negative
edited Jan 22 '14 at 17:30
answered Sep 21 '13 at 16:58
Stefan TStefan T
40747
40747
This can overflow when a and b are both large numbers, so it is not a correct solution.
– Trixie Wolf
Sep 12 '18 at 15:49
add a comment |
This can overflow when a and b are both large numbers, so it is not a correct solution.
– Trixie Wolf
Sep 12 '18 at 15:49
This can overflow when a and b are both large numbers, so it is not a correct solution.
– Trixie Wolf
Sep 12 '18 at 15:49
This can overflow when a and b are both large numbers, so it is not a correct solution.
– Trixie Wolf
Sep 12 '18 at 15:49
add a comment |
Java actually has no modulo operator the way C does. % in Java is a remainder operator. On positive integers, it works exactly like modulo, but it works differently on negative integers and, unlike modulo, can work with floating point numbers as well. Still, it's rare to use % on anything but positive integers, so if you want to call it a modulo, then feel free!
add a comment |
Java actually has no modulo operator the way C does. % in Java is a remainder operator. On positive integers, it works exactly like modulo, but it works differently on negative integers and, unlike modulo, can work with floating point numbers as well. Still, it's rare to use % on anything but positive integers, so if you want to call it a modulo, then feel free!
add a comment |
Java actually has no modulo operator the way C does. % in Java is a remainder operator. On positive integers, it works exactly like modulo, but it works differently on negative integers and, unlike modulo, can work with floating point numbers as well. Still, it's rare to use % on anything but positive integers, so if you want to call it a modulo, then feel free!
Java actually has no modulo operator the way C does. % in Java is a remainder operator. On positive integers, it works exactly like modulo, but it works differently on negative integers and, unlike modulo, can work with floating point numbers as well. Still, it's rare to use % on anything but positive integers, so if you want to call it a modulo, then feel free!
answered Jan 15 '10 at 17:57
Greg CharlesGreg Charles
94121231
94121231
add a comment |
add a comment |
The code runs much faster without using modulo:
public boolean isEven(int a)
return ( (a & 1) == 0 );
public boolean isOdd(int a)
return ( (a & 1) == 1 );
4
Premature optimization much?
– Lluis Martinez
Sep 25 '12 at 10:07
3
This looks much cleaner than the accepted answer. This has nothing to do with premature optimization. Its simply better, -- if it works.
– AlexWien
Jul 15 '13 at 19:39
3
@LluisMartinez This is one of the most misquoted sayings in computing. The full quotation is "Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.". Which actually means something quite different.
– user207421
Nov 17 '15 at 10:35
3
@EJP You're probably right. I did a test (loop with 1 million iterations) took 4000 nanoseconds with modulo, 2500 nanoseconds with logical and.
– Lluis Martinez
Nov 18 '15 at 0:43
add a comment |
The code runs much faster without using modulo:
public boolean isEven(int a)
return ( (a & 1) == 0 );
public boolean isOdd(int a)
return ( (a & 1) == 1 );
4
Premature optimization much?
– Lluis Martinez
Sep 25 '12 at 10:07
3
This looks much cleaner than the accepted answer. This has nothing to do with premature optimization. Its simply better, -- if it works.
– AlexWien
Jul 15 '13 at 19:39
3
@LluisMartinez This is one of the most misquoted sayings in computing. The full quotation is "Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.". Which actually means something quite different.
– user207421
Nov 17 '15 at 10:35
3
@EJP You're probably right. I did a test (loop with 1 million iterations) took 4000 nanoseconds with modulo, 2500 nanoseconds with logical and.
– Lluis Martinez
Nov 18 '15 at 0:43
add a comment |
The code runs much faster without using modulo:
public boolean isEven(int a)
return ( (a & 1) == 0 );
public boolean isOdd(int a)
return ( (a & 1) == 1 );
The code runs much faster without using modulo:
public boolean isEven(int a)
return ( (a & 1) == 0 );
public boolean isOdd(int a)
return ( (a & 1) == 1 );
answered Oct 12 '10 at 16:48
michaelmichael
11112
11112
4
Premature optimization much?
– Lluis Martinez
Sep 25 '12 at 10:07
3
This looks much cleaner than the accepted answer. This has nothing to do with premature optimization. Its simply better, -- if it works.
– AlexWien
Jul 15 '13 at 19:39
3
@LluisMartinez This is one of the most misquoted sayings in computing. The full quotation is "Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.". Which actually means something quite different.
– user207421
Nov 17 '15 at 10:35
3
@EJP You're probably right. I did a test (loop with 1 million iterations) took 4000 nanoseconds with modulo, 2500 nanoseconds with logical and.
– Lluis Martinez
Nov 18 '15 at 0:43
add a comment |
4
Premature optimization much?
– Lluis Martinez
Sep 25 '12 at 10:07
3
This looks much cleaner than the accepted answer. This has nothing to do with premature optimization. Its simply better, -- if it works.
– AlexWien
Jul 15 '13 at 19:39
3
@LluisMartinez This is one of the most misquoted sayings in computing. The full quotation is "Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.". Which actually means something quite different.
– user207421
Nov 17 '15 at 10:35
3
@EJP You're probably right. I did a test (loop with 1 million iterations) took 4000 nanoseconds with modulo, 2500 nanoseconds with logical and.
– Lluis Martinez
Nov 18 '15 at 0:43
4
4
Premature optimization much?
– Lluis Martinez
Sep 25 '12 at 10:07
Premature optimization much?
– Lluis Martinez
Sep 25 '12 at 10:07
3
3
This looks much cleaner than the accepted answer. This has nothing to do with premature optimization. Its simply better, -- if it works.
– AlexWien
Jul 15 '13 at 19:39
This looks much cleaner than the accepted answer. This has nothing to do with premature optimization. Its simply better, -- if it works.
– AlexWien
Jul 15 '13 at 19:39
3
3
@LluisMartinez This is one of the most misquoted sayings in computing. The full quotation is "Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.". Which actually means something quite different.
– user207421
Nov 17 '15 at 10:35
@LluisMartinez This is one of the most misquoted sayings in computing. The full quotation is "Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.". Which actually means something quite different.
– user207421
Nov 17 '15 at 10:35
3
3
@EJP You're probably right. I did a test (loop with 1 million iterations) took 4000 nanoseconds with modulo, 2500 nanoseconds with logical and.
– Lluis Martinez
Nov 18 '15 at 0:43
@EJP You're probably right. I did a test (loop with 1 million iterations) took 4000 nanoseconds with modulo, 2500 nanoseconds with logical and.
– Lluis Martinez
Nov 18 '15 at 0:43
add a comment |
if (a % 2 == 0)
else
add a comment |
if (a % 2 == 0)
else
add a comment |
if (a % 2 == 0)
else
if (a % 2 == 0)
else
edited Sep 18 '08 at 7:15
Chris Jester-Young
184k39342399
184k39342399
answered Sep 18 '08 at 5:18
J D OConalJ D OConal
621413
621413
add a comment |
add a comment |
you should examine the specification before using 'remainder' operator % :
http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.17.3
// bad enough implementation of isEven method, for fun. so any worse?
boolean isEven(int num)
num %= 10;
if(num == 1)
return false;
else if(num == 0)
return true;
else
return isEven(num + 2);
isEven = isEven(a);
add a comment |
you should examine the specification before using 'remainder' operator % :
http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.17.3
// bad enough implementation of isEven method, for fun. so any worse?
boolean isEven(int num)
num %= 10;
if(num == 1)
return false;
else if(num == 0)
return true;
else
return isEven(num + 2);
isEven = isEven(a);
add a comment |
you should examine the specification before using 'remainder' operator % :
http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.17.3
// bad enough implementation of isEven method, for fun. so any worse?
boolean isEven(int num)
num %= 10;
if(num == 1)
return false;
else if(num == 0)
return true;
else
return isEven(num + 2);
isEven = isEven(a);
you should examine the specification before using 'remainder' operator % :
http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.17.3
// bad enough implementation of isEven method, for fun. so any worse?
boolean isEven(int num)
num %= 10;
if(num == 1)
return false;
else if(num == 0)
return true;
else
return isEven(num + 2);
isEven = isEven(a);
answered Jan 18 '11 at 15:41
kiotokioto
6814
6814
add a comment |
add a comment |
Also, mod can be used like this:
int a = 7;
b = a % 2;
b
would equal 1. Because 7 % 2 = 1
.
it is probably a mistake to use compound operators in an example for beginners, and without output.
– Stu Thompson
Sep 18 '08 at 6:48
This is probably true.
– jjnguy
Sep 18 '08 at 15:04
add a comment |
Also, mod can be used like this:
int a = 7;
b = a % 2;
b
would equal 1. Because 7 % 2 = 1
.
it is probably a mistake to use compound operators in an example for beginners, and without output.
– Stu Thompson
Sep 18 '08 at 6:48
This is probably true.
– jjnguy
Sep 18 '08 at 15:04
add a comment |
Also, mod can be used like this:
int a = 7;
b = a % 2;
b
would equal 1. Because 7 % 2 = 1
.
Also, mod can be used like this:
int a = 7;
b = a % 2;
b
would equal 1. Because 7 % 2 = 1
.
edited Jan 15 '10 at 17:51
answered Sep 18 '08 at 5:19
jjnguyjjnguy
108k44269312
108k44269312
it is probably a mistake to use compound operators in an example for beginners, and without output.
– Stu Thompson
Sep 18 '08 at 6:48
This is probably true.
– jjnguy
Sep 18 '08 at 15:04
add a comment |
it is probably a mistake to use compound operators in an example for beginners, and without output.
– Stu Thompson
Sep 18 '08 at 6:48
This is probably true.
– jjnguy
Sep 18 '08 at 15:04
it is probably a mistake to use compound operators in an example for beginners, and without output.
– Stu Thompson
Sep 18 '08 at 6:48
it is probably a mistake to use compound operators in an example for beginners, and without output.
– Stu Thompson
Sep 18 '08 at 6:48
This is probably true.
– jjnguy
Sep 18 '08 at 15:04
This is probably true.
– jjnguy
Sep 18 '08 at 15:04
add a comment |
The remainder operator in Java is %
and the modulo operator can be expressed as
public int mod(int i, int j)
int rem = i % j;
if (j < 0 && rem > 0)
return rem + j;
if (j > 0 && rem < 0)
return rem + j;
return rem;
add a comment |
The remainder operator in Java is %
and the modulo operator can be expressed as
public int mod(int i, int j)
int rem = i % j;
if (j < 0 && rem > 0)
return rem + j;
if (j > 0 && rem < 0)
return rem + j;
return rem;
add a comment |
The remainder operator in Java is %
and the modulo operator can be expressed as
public int mod(int i, int j)
int rem = i % j;
if (j < 0 && rem > 0)
return rem + j;
if (j > 0 && rem < 0)
return rem + j;
return rem;
The remainder operator in Java is %
and the modulo operator can be expressed as
public int mod(int i, int j)
int rem = i % j;
if (j < 0 && rem > 0)
return rem + j;
if (j > 0 && rem < 0)
return rem + j;
return rem;
answered Jul 28 '10 at 15:08
eljensoeljenso
12.1k54862
12.1k54862
add a comment |
add a comment |
The modulo operator is % (percent sign). To test for evenness or generally do modulo for a power of 2, you can also use & (the and operator) like isEven = !( a & 1 ).
add a comment |
The modulo operator is % (percent sign). To test for evenness or generally do modulo for a power of 2, you can also use & (the and operator) like isEven = !( a & 1 ).
add a comment |
The modulo operator is % (percent sign). To test for evenness or generally do modulo for a power of 2, you can also use & (the and operator) like isEven = !( a & 1 ).
The modulo operator is % (percent sign). To test for evenness or generally do modulo for a power of 2, you can also use & (the and operator) like isEven = !( a & 1 ).
answered Sep 18 '08 at 5:18
jjrvjjrv
3,27413049
3,27413049
add a comment |
add a comment |
Another way is:
boolean isEven = false;
if((a % 2) == 0)
isEven = true;
But easiest way is still:
boolean isEven = (a % 2) == 0;
Like @Steve Kuo said.
add a comment |
Another way is:
boolean isEven = false;
if((a % 2) == 0)
isEven = true;
But easiest way is still:
boolean isEven = (a % 2) == 0;
Like @Steve Kuo said.
add a comment |
Another way is:
boolean isEven = false;
if((a % 2) == 0)
isEven = true;
But easiest way is still:
boolean isEven = (a % 2) == 0;
Like @Steve Kuo said.
Another way is:
boolean isEven = false;
if((a % 2) == 0)
isEven = true;
But easiest way is still:
boolean isEven = (a % 2) == 0;
Like @Steve Kuo said.
answered May 12 '14 at 13:44
brothers28brothers28
1,1011421
1,1011421
add a comment |
add a comment |
In Java it is the %
operator:
15.17.3. Remainder Operator %
Note that there is also floorMod
in the java.lang.Math
class which will give a different result from %
for arguments with different signs:
public static int floorMod(int x, int y)
add a comment |
In Java it is the %
operator:
15.17.3. Remainder Operator %
Note that there is also floorMod
in the java.lang.Math
class which will give a different result from %
for arguments with different signs:
public static int floorMod(int x, int y)
add a comment |
In Java it is the %
operator:
15.17.3. Remainder Operator %
Note that there is also floorMod
in the java.lang.Math
class which will give a different result from %
for arguments with different signs:
public static int floorMod(int x, int y)
In Java it is the %
operator:
15.17.3. Remainder Operator %
Note that there is also floorMod
in the java.lang.Math
class which will give a different result from %
for arguments with different signs:
public static int floorMod(int x, int y)
edited Mar 12 '18 at 10:37
answered Mar 4 '18 at 12:02
RolandRoland
2,56243885
2,56243885
add a comment |
add a comment |
An alternative to the code from @Cody:
Using the modulus operator:
bool isEven = (a % 2) == 0;
I think this is marginally better code than writing if/else, because there is less duplication & unused flexibility. It does require a bit more brain power to examine, but the good naming of isEven
compensates.
2
It's a remainder operator, not a modulus operator.
– user207421
Mar 30 '16 at 1:53
@EJP ok. Then what is the modulus operator?
– TheRealChx101
Jul 19 '18 at 22:29
add a comment |
An alternative to the code from @Cody:
Using the modulus operator:
bool isEven = (a % 2) == 0;
I think this is marginally better code than writing if/else, because there is less duplication & unused flexibility. It does require a bit more brain power to examine, but the good naming of isEven
compensates.
2
It's a remainder operator, not a modulus operator.
– user207421
Mar 30 '16 at 1:53
@EJP ok. Then what is the modulus operator?
– TheRealChx101
Jul 19 '18 at 22:29
add a comment |
An alternative to the code from @Cody:
Using the modulus operator:
bool isEven = (a % 2) == 0;
I think this is marginally better code than writing if/else, because there is less duplication & unused flexibility. It does require a bit more brain power to examine, but the good naming of isEven
compensates.
An alternative to the code from @Cody:
Using the modulus operator:
bool isEven = (a % 2) == 0;
I think this is marginally better code than writing if/else, because there is less duplication & unused flexibility. It does require a bit more brain power to examine, but the good naming of isEven
compensates.
answered Sep 18 '08 at 19:19
Jay BazuziJay Bazuzi
31.5k1094157
31.5k1094157
2
It's a remainder operator, not a modulus operator.
– user207421
Mar 30 '16 at 1:53
@EJP ok. Then what is the modulus operator?
– TheRealChx101
Jul 19 '18 at 22:29
add a comment |
2
It's a remainder operator, not a modulus operator.
– user207421
Mar 30 '16 at 1:53
@EJP ok. Then what is the modulus operator?
– TheRealChx101
Jul 19 '18 at 22:29
2
2
It's a remainder operator, not a modulus operator.
– user207421
Mar 30 '16 at 1:53
It's a remainder operator, not a modulus operator.
– user207421
Mar 30 '16 at 1:53
@EJP ok. Then what is the modulus operator?
– TheRealChx101
Jul 19 '18 at 22:29
@EJP ok. Then what is the modulus operator?
– TheRealChx101
Jul 19 '18 at 22:29
add a comment |
protected by bummi May 12 '14 at 13:35
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?