C programming Write a C program called div.cthat implements division on two unsi
ID: 3667002 • Letter: C
Question
C programming
Write a C program called div.cthat implements division on two unsigned integers.
1.Name your executable div.out
2.You cannot use division in your solution
3.Arguments should be accepted from the command line
1.the first argument is the dividend
2.The second argument is divisor
4.Your program should display the quotient and remainder after doing the division
5.Your program must complete in O(1) time
1.This is possible because an integer is 32 bits long and so the loop that does the division should not take longer than 32 iterations.
2.Because of this restriction the following solution is not acceptable as it does not meet the O requirements
void bad_div(unsigned int dividend,
unsigned int divisor,
unsigned int* quotient,
unsigned int *remainder){
*quotient = 0;
while(dividend >= divisor){
(*quotient)++;
dividend -= divisor;
}
*remainder = dividend;
}
Explanation / Answer
//Division using bitwise shift
#include <stdio.h>
int division(int dividend, int divisor, int origdiv, int * remainder)
{
int quotient = 1;
if (dividend == divisor)
{
*remainder = 0;
return 1;
}
else if (dividend < divisor)
{
*remainder = dividend;
return 0;
}
while (divisor <= dividend)
{
divisor = divisor << 1;
quotient = quotient << 1;
}
if (dividend < divisor)
{
divisor >>= 1;
quotient >>= 1;
}
quotient = quotient + division(dividend - divisor, origdiv, origdiv, remainder);
return quotient;
}
int main()
{
int dividend;
int divisor;
int rem = 0;
printf (" Enter the Dividend: ");
scanf("%d", ÷nd);
printf(" Enter the Divisor: ");
scanf("%d", &divisor);
printf("Quotient : %d ", division(dividend, divisor, divisor, &rem));
printf("Remainder: %d ", rem);
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.