xyvyre
xyvyre

Reputation: 175

Dividing an Two number Using Loop Statement

hi i'm doing a java activity that will divide the two given numbers without using the "/" operator. I want to use a loop statement.

System.out.print("Enter Divident: ");
int ans1 = Integer.parseInt(in.readLine());
System.out.print("Enter Divisor: ");
int ans2 = Integer.parseInt(in.readLine());

The output is:

  Enter Dividend: 25
  Enter Divisor 5
  5

How can solve this without using this "ans1/ans2"

Upvotes: 3

Views: 9725

Answers (6)

Farnabaz
Farnabaz

Reputation: 4066

if you really want to use loop to divide two numbers, you can write it like code below

 int c=0;
 while(ans1 >= ans2){
     ans1 -= ans2;
     c++;
 }

after loop c equals quotient and ans1 equals reminder of division

if abs1 and abs2 are signed numbers, below code should be work for division

 boolean n1 = (ans1 & (1<<31))!=0;
 boolean n2 = (ans2 & (1<<31))!=0;
 ans1 = Math.abs(ans1);
 ans2 = Math.abs(ans2);

 int c=0;
 while(ans1 >= ans2){
     ans1 -= ans2;
     c++;
 }
 if(!n1 && n2) c = -c;
 else if(n1 && !n2){
     c = -c;
     if(ans1 > 0){
         ans1 = ans2 - ans1;
         c--;
     }
 }else if(n1 && n2){
     if(ans1 > 0){
         ans1 = ans2 - ans1;
         c++;
     }
 }

Upvotes: 6

Aakash Anuj
Aakash Anuj

Reputation: 3871

You can do it in the following way:

System.out.print("Enter Divident: ");
int ans1 = Integer.parseInt(in.readLine());
System.out.print("Enter Divisor: ");
int ans2 = Integer.parseInt(in.readLine());
int count=0;
while(ans1>=ans2)
{
ans1=ans1-ans2;
count++;
}
System.out.println(count);

Upvotes: 0

Shashank Kadne
Shashank Kadne

Reputation: 8101

Something like below ?

int i=1;
        int mul;
        while(true)
        {
            mul = i++;
            if(mul*(ans2)==ans1)
            {
                System.out.println(mul);
                break;
            }
            else if(mul*(ans2)>ans1)
            {
                System.out.println("Cannot be divided");
                break;
            }
        }

Upvotes: -1

mishadoff
mishadoff

Reputation: 10789

BigInteger do the trick witout / operator, literally.

(new BigInteger(ans1 + "")).divide(new BigInteger(ans2 + ""))

Upvotes: 0

Hernan Velasquez
Hernan Velasquez

Reputation: 2820

Using recursion:

//  Calculate: a / b
public int divide (int a, int b) {
    if ( a < b ) {
        return 0;
    } else {
        return 1 + divide ( a - b, b );
    }
}

Upvotes: 1

Jon Taylor
Jon Taylor

Reputation: 7905

If you really want to do it without the / operator and im guessing probably without shifting either the simplest loop method would be to count the number of times you need to subtract ans2 from ans1 without the remainder going below ans1.

Pseudo code:

numtimes init at 0
counter init at ans1
while counter is greater than ans2
    subtract ans2 from counter
    numtimes increase by 1

check numtimes

Upvotes: 0

Related Questions