Write a C++ program to divide two integers (dividend and divisor) without using multiplication, division and mod operator

  • برمجة سي بلس بلس
  • برمجة

Write a C++ program to divide two integers (dividend and divisor) without using multiplication, division and mod operator

Sample Output:

Dividend 7 Divisor 2
Result: 3
Dividend -17 Divisor 5
Result: -3
Dividend 35 Divisor 7
Result: 5

الأجوبة

#include <iostream>
using namespace std;
int divide_result(int dividend_num, int divisor_num) {
       if (dividend_num == INT_MIN && divisor_num == -1)
       {
           return INT_MAX;
       }
       bool minus = ((dividend_num > 0) ^ (divisor_num > 0));
       long long num = labs(dividend_num);
       long long div = labs(divisor_num);
       int ans = 0;
       while (num >= div)
       {
           long long temp = div;
           long long mul = 1;
           while(num >= (temp << 1))
           {
               mul <<= 1;
               temp <<= 1;
           }
           ans += mul;
           num -= temp;
       }
       return minus ? -ans: ans;
   }
int main(void)
{
   int dividend_num = 7;
   int divisor_num = 2;
   cout << "\nDividend " << dividend_num << " Divisor " << divisor_num << endl;
   cout << "Result: " << divide_result(dividend_num, divisor_num) << endl;
   dividend_num = -17;
   divisor_num = 5;
   cout << "\nDividend " << dividend_num << " Divisor " << divisor_num << endl;
   cout << "Result: " << divide_result(dividend_num, divisor_num) << endl;
   dividend_num = 35;
   divisor_num = 7;
   cout << "\nDividend " << dividend_num << " Divisor " << divisor_num << endl;
   cout << "Result: " << divide_result(dividend_num, divisor_num) << endl;
   return 0;
}
هل كان المحتوى مفيد؟

تبحث عن مدرس اونلاين؟

محتاج مساعدة باختيار المدرس الافضل؟ تواصل مع فريقنا الان لمساعدتك بتأمين افضل مدرس
ماهو التخصص الذي تبحث عنه؟
اكتب هنا...