Extended Euclidean Algorithm in RSA
First, 40 = 3*13 + 1

So, we have found 1 in the first step.
Then I can write 1 as following:

1 = 40 - 3*13 and this is equivalent to

1 = 40 - 13*3. 40 is equivalent to 0 mod40.

1 = -13*3. Here we get the inverse of 3 as -13 which is equivalent to 27.