Write a C# program to divide two given integers (dividend and divisor) and get the quotient without using multiplication, division and mod operator

  • برمجة سي شارب
  • برمجة

Write a C# program to divide two given integers (dividend and divisor) and get the quotient without using multiplication, division and mod operator. 
Expected Output:
Dividend = 7, Divisor = 3
Quotient= 2
Dividend = -17, Divisor = 5
Quotient= -3
Dividend = 35, Divisor = 7
Quotient= 5

الأجوبة

using System;
using System.Text;
namespace exercises {
  class Program {
    static void Main(string[] args) {
      int dividend, divisor;
      dividend = 7;
      divisor = 3;
      if (divisor > 0) {
        Console.WriteLine("Dividend = " + dividend + ", Divisor = " + divisor);
        Console.WriteLine("Quotient= " + Divide(dividend, divisor));
      }
      dividend = -17;
      divisor = 5;
      if (divisor > 0) {
        Console.WriteLine("Dividend = " + dividend + ", Divisor = " + divisor);
        Console.WriteLine("Quotient= " + Divide(dividend, divisor));
      }
      dividend = 35;
      divisor = 7;
      if (divisor > 0) {
        Console.WriteLine("Dividend = " + dividend + ", Divisor = " + divisor);
        Console.WriteLine("Quotient= " + Divide(dividend, divisor));
      }

    }
    public static int Divide(int dividend, int divisor) {
      uint x = dividend > 0 ? (uint) dividend : (uint) - dividend;
      uint y = divisor > 0 ? (uint) divisor : (uint) - divisor;
      uint result = 0, z = 0;
      var idx = 0;
      while (x >= y) {
        z = y;
        for (idx = 0; x >= z && z != 0; idx++, z *= 2) {
          x -= z;
          result += (uint) 1 << idx;
        }
      }
      return (dividend ^ divisor) >> 31 == -1 ?
        (int) - result :
        result > int.MaxValue ? int.MaxValue : (int) result;
    }
  }
}
هل كان المحتوى مفيد؟

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

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