-1

How do I use JavaScript to calculate the x value in this formula?

(x * y) % z = 1

y and z are known integers.

For example, y = 7, z = 20. 3 multiplied by 7 results into 21, that divided by 20 results into remainder of 1. Solution x = 3.

(3 * 7) % 20 = 1

j08691
  • 204,283
  • 31
  • 260
  • 272
MikkoP
  • 4,864
  • 16
  • 58
  • 106
  • 1
    Have you tried anything? – j08691 Jan 09 '14 at 18:52
  • Is this homework for a class? – pseudosavant Jan 09 '14 at 19:00
  • @j08691 Why is that always the first question? `x = eval("((x * " + y + ") % " + z + " = 1)");` doesn't work at least. That's what I've tried. Results into `Invalid left-hand side in assignment ` – MikkoP Jan 09 '14 at 19:09
  • @pseudosavant No it's not. – MikkoP Jan 09 '14 at 19:09
  • Are you sure x isn't equal to 23? This equation doesn't guarantee a single answer. Regarding your attempt, Javascript cannot do symbolic algebra, you will need to write a function of y and z that returns x. – Matt R Jan 09 '14 at 19:31
  • It's always the first question because we like to see that you've put some effort into trying to resolve your problem, and haven't come here as a first resort for someone to do your work for you. – j08691 Jan 09 '14 at 20:55

2 Answers2

1

This is a math question, not a JavaScript question. Use the Extended Euclidean Algorithm. For example, to find the inverse of 7 modulo 20, start with these two equations:

20 =  0•7 + 1•20.
 7 =  1•7 + 0•20.

Next, divide the two numbers on the left (20/7) and take the integer part (2). The subtract that times the bottom equation from the one above it:

20 =  0•7 + 1•20.
 7 =  1•7 + 0•20.
 6 = -2•7 + 1•20.

Repeat: The integer part of 7/6 is 1. Subtract one times the bottom equation from the one above it. The new equation is:

 1 =  3•7 - 1•20.

Now you can see that 3 times 7 is 1 modulo 20. (Simultaneously, -1 times 20 is 1 modulo 7.)

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
0

Well, there's more than one number that is valid for x. x could also be 23 in this case (23 * 7 = 161, and 161 % 20 = 1). So you need to express the problem a bit differently as a starting point, such as "what is the lowest x that can solve the equation?"

If you're solving that then it is suddenly a different problem. You then only need to solve for two possibilities: (x * y) - z = 1, and (x * y) = 1. From there you can do a little algebra to solve for x.

super_seabass
  • 1,116
  • 7
  • 20