简体   繁体   中英

Implementing (A ^ B) % C i.e, pow(A, B) % C

I am given with three integers A, B and C. I need to implement a program to perform the operation A^B modulus C. I without thinking much, wrote the following code:-

public int Mod(int A, int B, int C) 
{
    return (int)Math.pow(A,B) % C;
}

testcase: A = -1, B = 1, C = 20, the expected o/p was 19 whereas my code gave -1 as output.

I found out that this approach is incorrect when there is a negative number, in this example, when A < 0. I referred to explanations in few websites, but was unable to understand this behavior. Please help me on this one. Thank you.

% Operator in Java

In java, when calculating

A % B

the answer is produced according to following conditions:

When the dividend is negative , the answer produced will also be negative and when the dividend is positive , the answer produced will also be positive .

Do note that this behavior is language specific . In python, the above program will produce 19 as output.


Flaw in the code

If one only wants A % B to produce positive results , then simply using A % B will produce wrong output because of reasons mentioned above.

Also, calculating A^B % C where B can take large values directly is not the right approach. I suggest you use fast exponentiation to do so. It is a famous algorithm and you can easily find it online.


Solution

If you want only positive result , use this:

r = a % b > 0 ? a % b : Math.abs(b) + a % b;

Here r is remainder, a is dividend and b is divisor.


I hope I have helped you. If you want to understand why this happens, do comment and I will be happy to edit my answer to help you.

There is no 'modulus' operator in Java; there is a remainder operator .

Negative one to the power one is negative one.

The remainder of dividing negative one by 20 is negative one.

The JLS (link above) specifically says that the sign of the result is the same as the sign of the left-hand side. Thus -1 and not +19.

The definition of % is

The remainder operation for operands that are integers after binary numeric promotion (§5.6.2) produces a result value such that (a/b)*b+(a%b) is equal to a.

function pow(A,B,C)
{
    if(A == 0) {
        return 0;
    }
    else if(B == 0) {
        return 1;
    }
    else if(B%2 == 0) {
        let half = this.power(A,Math.floor(B/2),C);
        return (half * half)%C;
    }
    else {

        return ((this.power(A,B-1,C)) * A%C)%C;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM