Sunday, 20 November 2016

How to calculate remainder without using mod(%) operator.


There are two ways to calculate remainder without using mod(%) operator.
        1) Using divide operator
        2) Using iterative way to repeative addition of given dividend.


1) Using divide operator

Algorithm:
Step 1: Divide the given input with the given dividend  value and again multiple with dividend.
Step 2: Again subtract the above result from the given input value;

Code:

public class ModRemainderUsingDivide {

public static void main(String[] args) {

int input = 145;
int dividend = 14;
int remainder  = input - ((input/dividend)*dividend);
System.out.println(" Remainder :"+remainder);
}

}

2) Using iterative way to repeative addition of given dividend.

When interviewer asked me to write logic, i wrote above program. But still he don't want to use the dividend operator. So i came up with the solution called repeative addition of given dividend logic.

Code:

public class ModRemainder {


public static void main(String[] args) {

// TODO Auto-generated method stub
int input = 122;
int dividend = 11;
int quotient = 0;
int remainder = 0;
int temp = 0;
while(temp< input) {
temp = temp+dividend;
quotient++;
}

remainder = input - (temp-dividend);

System.out.println(" Quotient :"+(quotient-1));
System.out.println(" Remainder :"+remainder);
}

}







If you like the above solution . Please share this blog

No comments:

Post a Comment

s