How to find remainder without using MODULUS OPERATOR?

I am new in programming. Now I am trying to find remainder without using modulus operator. Can anyone help me?

If you can use the integer division operator, you could use

mod(x,y) = (x - y*(x/y))
2 Likes

divide and then subtract the multiple

#include<stdio.h>
main()
{
int n,i,k;
float j,rem,a=9,b=10,c=1;
printf(“enter the dividend and divisor”);
scanf("%d%d",&n,&i);
j=(float)n/i;
rem=(j-n/i)*i;
k =((j-n/i)*i);
if(rem>k && rem<k+1 && rem>(float)k+(a/b))
rem=k+1;
else if(rem>k && rem<(float)k+(c/b))
rem=k;
printf(“remainder=%f”,rem);
getch();
}

1 Like

The straight forward way is to use division and multiplication and get y%x = y - x*(y/x)
But I guess restriction % should also not allow / and * operators. So to go with just the bitwise operators you can do the following. Calculate x<<i till it is lower than or equal to y and subtract from highest value of x<<i to lowest ie x if you can from y iteratively.

int p = x;
while(p<y) p<<=1;
while(p>=x) {
    if(y>=p)y-=p; p>>=1;
}
return y;
3 Likes