user2229953
user2229953

Reputation: 1559

Modulus in Java

I want to get the value of an unknown number in equation containing modulus % in Java

For example:

x % 26 = y if I have the value of y how can I get x

Upvotes: 1

Views: 1093

Answers (2)

Ted Hopp
Ted Hopp

Reputation: 234795

The problem is that there are either zero solutions (if Math.abs(y) >= 26) or an infinite1 number of values of x that satisfy that equation for a given y. The general answer is:

x = 26 * k + y

for any integer value of k. You can pick whatever k you want.2

1 In practice, the range will be limited by the range of integer values you are using. If x and y are int values, then you are limited by Integer.MAX_VALUE and Integer.MIN_VALUE. On the other hand, if they are BigInteger values, you don't have much in the way of range constraints.

2 Actually, the signs of x and y must be the same in Java, so you only have half of infinity to pick from. :-)

Upvotes: 11

Jonathan Kortleven
Jonathan Kortleven

Reputation: 615

You can't get the value of x, that's how modulus works. You just know x = 26 * k + y where k is an integer.

Upvotes: 2

Related Questions