What's the syntax for mod in java - java

As an example in pseudocode:
if ((a mod 2) == 0)
{
isEven = true;
}
else
{
isEven = false;
}

Instead of the modulo operator, which has slightly different semantics, 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;

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.

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. ;)

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;
}

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!

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

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 );
}

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)

As others have pointed out, the % (remainder) operator is not the same as the mathematical
mod modulus operation/function.
mod vs %
The x mod n function maps x to n in the range of [0,n).
Whereas the x % n operator maps x to n in the range of (-n,n).
In order to have a method to use the mathematical modulus operation and not
care about the sign in front of x one can use:
((x % n) + n) % n
Maybe this picture helps understand it better (I had a hard time wrapping my head around this first)

if (a % 2 == 0) {
} else {
}

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);

Also, mod can be used like this:
int a = 7;
b = a % 2;
b would equal 1. Because 7 % 2 = 1.

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;
}

In Java, the mod operation can be performed as such:
Math.floorMod(a, b)
Note:
The mod operation is different from the remainder operation. In Java, the remainder operation can be performed as such:
a % b

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.

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 ).

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.

Related

Java integer division doesn't give floor for negative numbers

I was trying to use java's integer division, and it supposedly takes the floor. However, it rounds towards zero instead of the floor.
public class Main {
public static void main(String[] args) {
System.out.println(-1 / 100); // should be -1, but is 0
System.out.println(Math.floor(-1d/100d)); // correct
}
}
The problem is that I do not want to convert to a double/float because it needs to be efficient. I'm trying to solve this with a method, floorDivide(long a, long b). What I have is:
static long floorDivide(long a, long b) {
if (a < 0) {
// what do I put here?
}
return a / b;
}
How can I do this without a double/float?
floorDiv() from Java.Math that does exactly what you want.
static long floorDiv(long x, long y)
Returns the largest (closest to positive infinity) long value that is less than or equal to the algebraic quotient.
Take the absolute value, divide it, multiply it by -1.
Weird bug.
You can use
int i = (int) Math.round(doubleValToRound);
It will return a double value that you can cast into an int without lost of precission and without performance problems (casts haven't a great computational cost)
Also it's equivalent to
int a = (int) (doubleValToRound + 0.5);
//in your case
System.out.println((int) ((-1 / 100) + 0.5));
With this last one you won't have to enter into tedious and unnecesary "if" instructions. Like a good suit, its valid for every moment and has a higher portability for other languages.
This is ugly, but meets the requirement to not use a double/float. Really you should just cast it to a double.
The logic here is take the floor of a negative result from the integer division if it doesn't divide evenly.
static long floorDivide(long a, long b)
{
if(a % b != 0 && ((a < 0 && b > 0) || (a > 0 && b < 0)))
{
return (a / b - 1);
}
else
{
return (a / b);
}
}
Just divide the two integers. then add -1 to the result (in case the absolute value of both numerator and denominator are not same). For example -3/3 gives you -1, the right answer without adding -1 to the division.
Since a bit late, but you need to convert your parameters to long or double
int result = (int) Math.floor( (double) -1 / 5 );
// result == -1
This worked for me elegantly.
I would use floorDiv() for a general case, as Frank Harper suggested.
Note, however, that when the divisor is a power of 2, the division is often substituted by a right shift by an appropriate number of bits, i.e.
x / d
is the same as
x >> p
when p = 0,1,...,30 (or 0,1,...,62 for longs), d = 2p and x is non-negative. This is not only more effective than ordinary division but gives the right result (in mathematical sense) when x is negative.

Divide two integers using bitwise operators

I have to divide two numbers by just using the bitwise operators. My code is as follows:
public class Solution {
public int divide(int dividend, int divisor) {
int c = 0, sign = 0;
if (dividend < 0) {
dividend = negate(dividend);
sign^=1;
}
if (divisor < 0) {
divisor = negate(divisor);
sign^=1;
}
if ( divisor != 0){
while (dividend >= divisor){
dividend = sub(dividend, divisor);
c++;
}
}
if (sign == 1){
c = negate(c);
}
return c;
}
private int negate(int number){
return add(~number,1);
}
private int sub(int x, int y){
return add(x,negate(y));
}
private int add(int x, int y){
while ( y != 0){
int carry = x&y;
x = x^y;
y = carry << 1;
}
return x;
}
}
I am getting a time out exception while running the code :
Last executed input:
2147483647
1
I added an extra check in the code like this :
if (divisor == 1){
return dividend;
}
but then on running the code again, I am getting a Time out exception like this:
Last executed input:
2147483647
2
Can you help me where I am going wrong with the code?
Since you are using a naïve implementation of the arithmetical operations, I assume it just takes too long, since it has to do roughly 1 billion of subtractions, each of which is a loop of 16 iterations on average. So it'd be about 5 seconds on a 3GHz CPU, if every inner step took 1 cycle. But since it obviously takes more, especially considering it's in java, I'd say you can easily expect something like a 1 minute running time. Perhaps java has a timeout check for the environment you are running it in.
I have to admit I haven't thoroughly verified your code and assumed it worked correctly algorithm-wise.
Think of how long division works, the pen-and-paper method for division we've all learnt at school.
Of course we've learnt it in base 10, but is there any reason why the same algorithm wouldn't work in base 2?
No, in fact it's easier because when you're doing the division step for each digit, the result is simply 1 if the part of the dividend above the divisor is greater than or equal to the divisor, and 0 otherwise.
And shifting the divisor and the result come out of the box too.

How to detect overflow on power in Java

I know that java.lang.Math provides a set of static methods to perform some operations (sum, difference, multiply, increment, decrement, negate, toInt), throwing an ArithmeticException on overflow.
Is there something similar for power?
No, there is nothing equivalent for pow built into Java. (The only pow methods built into Java are Math.pow, which accepts doubles and does not overflow in the same way integers do, and BigInteger.pow, which does not overflow because BigIntegers can be arbitrarily large.)
If third-party libraries are acceptable, though, Guava has e.g. IntMath.checkedPow, which does what you're looking for.
As Chirag said, integers throw exceptions when they overflow while doubles don't. Not to get too specific but, basically, doubles in memory are stored very similarly to scientific notation, in that they are some integer * 2^(some power), and thus never really overflow but multiply by such a large or small 2^(some power) that they completely lose their precision. So you can instead think of double overflow as when they completely lose their precision and are printed as either Infinity or -Infinity.
So, you will need to manually check that an overflow has occurred by checking if the resulting value is Double.POSITIVE_INFINITY or Double.NEGATIVE_INFINITY.
Here is some sample code to show what I mean:
public static void main(String[] args) throws Exception
{
double a = Double.MAX_VALUE; // highest possible double
double b = Double.MAX_VALUE; // highest possible double
if (Math.pow(a, b) == Double.POSITIVE_INFINITY || Math.pow(a, b) == Double.NEGATIVE_INFINITY)
{
throw new ArithmeticException("Double Overflow");
}
}
If it's fine to have your own implementation, you could do something like this:
private static final int[] maxBaseForExponent = IntStream.range(0, 30)
.map(e -> (int) Math.pow(Integer.MAX_VALUE, 1d / e)).toArray();
public static int powExact(int base, int exponent) {
if (exponent < 0) {
throw new ArithmeticException("Negative exponent");
}
if ((base < -1 || base > 1) && (exponent > 30 || base > maxBaseForExponent[exponent])
&& !(base == -2 && exponent == 31)) {
throw new ArithmeticException("Overflow");
}
switch (base) {
case -2:
return (exponent & 1) == 0 ? 1 << exponent : -1 << exponent;
case -1:
return (exponent & 1) == 0 ? 1 : -1;
case 0:
return exponent == 0 ? 1 : 0;
case 1:
return 1;
case 2:
return 1 << exponent;
default:
}
int result = 1;
while (exponent != 0) {
if ((exponent & 1) != 0) {
result *= base;
}
exponent >>= 1;
base *= base;
}
return result;
}
Took the algorithm from here, and modified it to check for overflow using an array which contains max base for each exponent from 0 to 30.
Integers are only 32 bits. so max value is 2^31 -1. ( If using BigInteger.pow. It is less efficient.)
So you can check manually and throw Exception if required
else use Math.pow which uses double.

Sum of squares of digits of an integer in Java

I am trying to write a recursive implementation of a method that takes a non-negative argument, and returns the sum of the squares of its digits. For example, sumSquareDigits(10) should return 1 and sumSquareDigits(103) should return 10.
This is my code :
public static int sumSquareDigits(int n) {
if (n < 10) return n^2;
return (((n % 10)^2) + sumSquareDigits(n/10));
}
For example for an given integer 625, it would be something like:
(625 % 10)^2 + (62,5 % 10)^2 + (6,25)^2 = 5^2 + 2^2 + (6,25)^2
which of course is wrong because the last term should be 6 and not 6,25. What I am looking for is a way to truncate 6,25 so that it becomes 6.
How do we do this? And I'd appreciate any hints to implement this function better (I'm new in Java).
Thanks!
In Java, ^ is not "to the power" of, it is the bitwise XOR operator. To perform powers in Java use Math.pow. Bear in mind that Math.pow returns a double so you will need to cast it to an int if you only want a whole number. E.g.
if (n < 10) return (int)Math.pow(n, 2);
Of course, as msandiford pointed out, if you only need to calculate powers of 2, it is probably easier to just multiply a number by itself. E.g.
if (n < 10) return n * n;
The ^ is for the bitwise XOR operator. You could use Math.pow, and cast the results to int since Math.pow returns a double:
public static int sumSquareDigits(int n) {
if (n < 10) return (int) Math.pow(n, 2);
return (int)((Math.pow((n % 10), 2)) + sumSquareDigits(n/10));
}
Or since it's only squared, just multiply the base by itself:
public static int sumSquareDigits(int n) {
if (n < 10) return n * n;
return ((n % 10) * (n % 10)) + sumSquareDigits(n/10);
}

Not sure how to describe this line of code

It works fine but I'm just not sure how it works, could anyone explain it? Thanks
public static int gcd(int a, int b) {
return b==0 ? a : gcd(b, a%b);
}
You have a ternary operator (bool ? x : y). Such an operator will evaluate the statement before the question mark. If that evaluates to true, x will be chosen, y otherwise.
This means its logic is equivalent to this:
public static int gcd(int a, int b)
{
if (b == 0)
return a;
else
return gcd(b, a % b);
}
Next, a % b calculates the modulo of the two numbers, which is the remainder of the integer division a / b. Eg: 7 % 2 results in 1 and 14 % 5 yields 4.
Algorithm: http://en.wikipedia.org/wiki/Greatest_common_divisor
Syntax:
return b==0? a :gcd(b, a%b)
means
if(b==0)
return a;
else
return gcd(b, a%b);
It's a recursive static method, which calculated gcd of two numbers.
Consider this invocation of this method -
int gcd = gcd(12, 6);
Your method body becomes equivalent to -
return 6==0 ? 12 : gcd(6, 12 % 6);
since 6 is not equal to zero, gcd gets called again. This time, it's something like this -
return 0 == 0 ? 6 : gcd(6, 0 % 6);
and since 0 == 0 is true, 6 gets returned, which is the greatest common divisor between 12 and 6.
It is the implementation of the euclids algorithm to find the greatest divisor. It uses a recursion.

Categories

Resources