C Exercises: Divide two given integers without using multiplication, division and mod operator
C Programming Practice: Exercise-15 with Solution
Write a C programming to divide two given integers without using multiplication, division and mod operator. Return the quotient after dividing.
C Code:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int divide_two(int dividend_num, int divisor_num)
{
int sign = (float) dividend_num / divisor_num > 0 ? 1 : -1;
unsigned int dvd = dividend_num > 0 ? dividend_num : -dividend_num;
unsigned int dvs = divisor_num > 0 ? divisor_num : -divisor_num;
unsigned int bit_num[33];
unsigned int i = 0;
long long d = dvs;
bit_num[i] = d;
while (d <= dvd) {
bit_num[++i] = d = d << 1;
}
i--;
unsigned int result = 0;
while (dvd >= dvs) {
if (dvd >= bit_num[i]) {
dvd -= bit_num[i];
result += (1<<i);
} else {
i--;
}
}
if (result > INT_MAX && sign > 0) {
return INT_MAX;
}
return (int) result * sign;
}
int main(void)
{
int dividend_num = 15;
int divisor_num = 3;
printf("Quotient after dividing %d and %d : %d", dividend_num, divisor_num, divide_two(dividend_num, divisor_num));
return 0;
}
Sample Output:
Quotient after dividing 15 and 3 : 5
Pictorial Presentation:
Flowchart:
C Programming Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a C programming to find the index of the first occurrence of a given string within another given string. If not found return -1.
Next: Write a C programming to find the length of the longest valid (correct-formed) parentheses substring of a given string.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
C Programming: Tips of the Day
Static variable inside of a function in C
The scope of variable is where the variable name can be seen. Here, x is visible only inside function foo().
The lifetime of a variable is the period over which it exists. If x were defined without the keyword static, the lifetime would be from the entry into foo() to the return from foo(); so it would be re-initialized to 5 on every call.
The keyword static acts to extend the lifetime of a variable to the lifetime of the programme; e.g. initialization occurs once and once only and then the variable retains its value - whatever it has come to be - over all future calls to foo().
Ref : https://bit.ly/3fOq7XP
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework