Monday, 14 August 2017

Divide two integers without using multiplication, division and mod operator

You are given one Dividend and Divisor. You need to find out the Quotient without using multiplication, division and mod operator.

For example :
Dividend=20 and Divisor=5 then Quotient=4
if Dividend=21 and Divisor=5, then Quotient=4

Sample code:

public class DivideTwoInt {

    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        System.out.println("Enter Integer to Dividend:  \n");
        int dividend=in.nextInt();
        System.out.println("Enter Divisor: \n");
        int divisor=in.nextInt();
        int count=checkDividend(dividend,divisor);
        System.out.println("Result is: "+count);

    }

    private static int checkDividend(int dividend, int divisor) {
        if(dividend==divisor)
            return 1;      
        if(dividend==0)
            return 0;
        if(divisor==0)
            return -1;
        int count=0;
        while(dividend>=divisor)
        {
            dividend=dividend-divisor;
            count=count+1;
        }
        return count;
    }
}



Sample Output 1:

Enter Integer to Dividend: 
20
Enter Divisor:
5
Result is: 4 


Sample output 2:

Enter Integer to Dividend: 
26
Enter Divisor:
5
Result is: 5

2 comments:

Use of Lamda Expression and Functional Interface in JAVA 8

In this blog, we are going to discuss one of the most important features of JAVA 8 which is Lamda Expression and Functional Interface. A...