Domanda

I need to do a MOD of a number which is a long datatype with 1965.

Something like this -

number % 1965

Will the above modulus result always be within 0 and 1964?

Or there are some cases in which it won't return any number between 0 and 1664?

I am using Java as programming language and I will be running my program on Ubuntu machines.

Initially I thought its a Math question but it depends mostly on the Compiler and Language... So kind of confused it will always return number between 0 and 1664 or there are some exception cases?

This is what I have in my method -

private static int getPartitionNumber() {
    return (int) (number % 1965);
}

UPDATE:

One thing I forgot to mention is, here number will always be positive number. Any negative number I am throwing IllegalArgumentException at the starting of the program.

È stato utile?

Soluzione

No, java's implementation of modulus will return a value in the range (-n, n) for the value x % n. I.e. If you have a negative number as the left operand, then the result will be negative. to get around this, try something like the following:

((x % n) + n) % n;

Which will return a value in the range [0,n)

EDIT (to reflect UPDATE in question)

In the case of positive numbers in the left operand, then simply x % n will produce numbers in the range [0,n) where x >= 0.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top