Old Person
Old Person

Reputation: 109

Moving modulus operator to the other side of the equation

I have a mathematical problem that is part of my programming problem

I have a statement like

a = b%30;

How can I calculate b in terms of a?

I gave it a thought but couldn't figure it out.

Upvotes: 6

Views: 9480

Answers (3)

Chris Rudd
Chris Rudd

Reputation: 809

As stated above, by definition

b == 30*n + a

Because of the constraints imposed by b%30, a must be between 0 and 29

However b is unbounded. there are (infinitely) many b for each a

Therefore you must have some other equation to apply to b or n to get a clear answer. I will call this f(b)

To solve for b programmatically you would also need a valid range for n, or at least a value to start at and a direction to move in:

# an example function, this would be unique to whatever your problem is
function f(b)
    return 100 <= b <= 1000

n = 0  # or whatever your start is
while not f(b)  # could also be f(n) depending on your needs
    n += 1  # or whatever your direction is
    b == 30*n + a

or if you want to collect several b's across a range of n

# an example function, this would be unique to whatever your problem is
function f(b)
    return 100 <= b <= 1000

results = array()
for n = 0 to 1e9 # or whatever your range is
    b == 30*n + a
    if f(b) then results.append(b)

Upvotes: 0

Pascal Cuoq
Pascal Cuoq

Reputation: 80325

First, obviously, there are in general several solutions for b for a given a.

If % is the remainder operator found in most programming languages, then the sign of a is critical. You know that this is a website for programming questions, right?

If |a|>=30, then there are no solutions

If a = 0, the solutions are the multiples of 30.

If 0 < a < 30, the solutions are all the b such that b = 30 * k + a for some positive integer k.

If -30 < a < 0, the solutions are all the b such that b = - (30 * k - a) for some positive integer k.

Upvotes: 3

arshajii
arshajii

Reputation: 129537

By definition,

b == 30*n + a

for some integer n.

Note that there are multiple b values that can give you the same a:

>>> b = 31
>>> b % 30
1
>>> b = 61
>>> b % 30
1

Upvotes: 8

Related Questions