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
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
I would love to see your comment and feedback.
ReplyDeleteNice Questions collection :)
ReplyDelete