Dividing an Two number Using Loop Statement

吃可爱长大的小学妹 提交于 2019-12-06 02:00:34

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++;
     }
 }

Using recursion:

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

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

BigInteger do the trick witout / operator, literally.

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

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);

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;
            }
        }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!