📌  相关文章
📜  将两个整数相除而不使用乘法,除法和mod运算符

📅  最后修改于: 2021-05-25 08:42:26             🧑  作者: Mango

给定两个整数,则说a和b。将a除以b后不使用乘法,除法和mod运算符。

例子:

Input : a = 10, b = 3
Output : 3

Input : a = 43, b = -8
Output :  -5 

方法:不断从除数中减去除数,直到除数小于除数。股息成为余数,减法的次数成为商。下面是上述方法的实现:

C++
// C++ implementation to Divide two
// integers without using multiplication,
// division and mod operator
#include 
using namespace std;
 
// Function to divide a by b and
// return floor value it
int divide(int dividend, int divisor) {
 
  // Calculate sign of divisor i.e.,
  // sign will be negative only iff
  // either one of them is negative
  // otherwise it will be positive
  int sign = ((dividend < 0) ^ (divisor < 0)) ? -1 : 1;
 
  // Update both divisor and
  // dividend positive
  dividend = abs(dividend);
  divisor = abs(divisor);
 
  // Initialize the quotient
  int quotient = 0;
  while (dividend >= divisor) {
    dividend -= divisor;
    ++quotient;
  }
 
  return sign * quotient;
}
 
// Driver code
int main() {
  int a = 10, b = 3;
  cout << divide(a, b) << "\n";
 
  a = 43, b = -8;
  cout << divide(a, b);
 
  return 0;
}


Java
/*Java implementation to Divide two
integers without using multiplication,
division and mod operator*/
 
import java.io.*;
 
class GFG
{
     
    // Function to divide a by b and
    // return floor value it
    static int divide(int dividend, int divisor)
    {
         
        // Calculate sign of divisor i.e.,
        // sign will be negative only iff
        // either one of them is negative
        // otherwise it will be positive
        int sign = ((dividend < 0) ^
                   (divisor < 0)) ? -1 : 1;
     
        // Update both divisor and
        // dividend positive
        dividend = Math.abs(dividend);
        divisor = Math.abs(divisor);
     
        // Initialize the quotient
        int quotient = 0;
         
        while (dividend >= divisor)
        {
            dividend -= divisor;
            ++quotient;
        }
     
        return sign * quotient;
    }   
     
    public static void main (String[] args)
    {
        int a = 10;
        int b = 3;
         
        System.out.println(divide(a, b));
         
        a = 43;
        b = -8;
         
        System.out.println(divide(a, b));
    }
}
 
// This code is contributed by upendra singh bartwal.


Python3
# Python 3 implementation to Divide two
# integers without using multiplication,
# division and mod operator
 
# Function to divide a by b and
# return floor value it
def divide(dividend, divisor):
 
    # Calculate sign of divisor i.e.,
    # sign will be negative only iff
    # either one of them is negative
    # otherwise it will be positive
    sign = -1 if ((dividend < 0) ^  (divisor < 0)) else 1
     
    # Update both divisor and
    # dividend positive
    dividend = abs(dividend)
    divisor = abs(divisor)
     
    # Initialize the quotient
    quotient = 0
    while (dividend >= divisor):
        dividend -= divisor
        quotient += 1
     
     
    return sign * quotient
 
 
# Driver code
a = 10
b = 3
print(divide(a, b))
a = 43
b = -8
print(divide(a, b))
 
# This code is contributed by
# Smitha Dinesh Semwal


C#
// C# implementation to Divide two without
// using multiplication, division and mod
// operator
using System;
 
class GFG {
     
    // Function to divide a by b and
    // return floor value it
    static int divide(int dividend, int divisor)
    {
         
        // Calculate sign of divisor i.e.,
        // sign will be negative only iff
        // either one of them is negative
        // otherwise it will be positive
        int sign = ((dividend < 0) ^
                (divisor < 0)) ? -1 : 1;
     
        // Update both divisor and
        // dividend positive
        dividend = Math.Abs(dividend);
        divisor = Math.Abs(divisor);
     
        // Initialize the quotient
        int quotient = 0;
         
        while (dividend >= divisor)
        {
            dividend -= divisor;
            ++quotient;
        }
     
        return sign * quotient;
    }
     
    public static void Main ()
    {
         
        int a = 10;
        int b = 3;
        Console.WriteLine(divide(a, b));
         
        a = 43;
        b = -8;
        Console.WriteLine(divide(a, b));
    }
}
 
// This code is contributed by vt_m.


PHP
= $divisor)
    {
        $dividend -= $divisor;
        ++$quotient;
    }
     
    return $sign * $quotient;
}
 
// Driver code
$a = 10;
$b = 3;
echo divide($a, $b)."\n";
 
$a = 43;
$b = -8;
echo divide($a, $b);
 
// This code is contributed by Sam007
?>


Javascript


C++
// C++ implementation to Divide two
// integers without using multiplication,
// division and mod operator
#include 
using namespace std;
 
// Function to divide a by b and
// return floor value it
int divide(long long dividend, long long divisor) {
 
  // Calculate sign of divisor i.e.,
  // sign will be negative only iff
  // either one of them is negative
  // otherwise it will be positive
  int sign = ((dividend < 0) ^
              (divisor < 0)) ? -1 : 1;
 
  // remove sign of operands
  dividend = abs(dividend);
  divisor = abs(divisor);
 
  // Initialize the quotient
  long long quotient = 0, temp = 0;
 
  // test down from the highest bit and
  // accumulate the tentative value for
  // valid bit
  for (int i = 31; i >= 0; --i) {
 
    if (temp + (divisor << i) <= dividend) {
      temp += divisor << i;
      quotient |= 1LL << i;
    }
  }
 
  return sign * quotient;
}
 
// Driver code
int main() {
  int a = 10, b = 3;
  cout << divide(a, b) << "\n";
 
  a = 43, b = -8;
  cout << divide(a, b);
 
  return 0;
}


Java
// Java implementation to Divide
// two integers without using
// multiplication, division
// and mod operator
import java.io.*;
import java.util.*;
 
// Function to divide a by b
// and return floor value it
class GFG
{
public static long divide(long dividend,
                        long divisor)
{
 
// Calculate sign of divisor
// i.e., sign will be negative
// only iff either one of them
// is negative otherwise it
// will be positive
long sign = ((dividend < 0) ^
            (divisor < 0)) ? -1 : 1;
 
// remove sign of operands
dividend = Math.abs(dividend);
divisor = Math.abs(divisor);
 
// Initialize the quotient
long quotient = 0, temp = 0;
 
// test down from the highest
// bit and accumulate the
// tentative value for
// valid bit
// 1<<31 behaves incorrectly and gives Integer
// Min Value which should not be the case, instead
  // 1L<<31 works correctly.
for (int i = 31; i >= 0; --i)
{
 
    if (temp + (divisor << i) <= dividend)
    {
        temp += divisor << i;
        quotient |= 1L << i;
    }
}
 
return (sign * quotient);
}
 
// Driver code
public static void main(String args[])
{
int a = 10, b = 3;
System.out.println(divide(a, b));
 
int a1 = 43, b1 = -8;
System.out.println(divide(a1, b1));
 
 
}
}
 
// This code is contributed
// by Akanksha Rai(Abby_akku)


Python3
# Python3 implementation to
# Divide two integers
# without using multiplication,
# division and mod operator
 
# Function to divide a by
# b and return floor value it
def divide(dividend, divisor):
     
    # Calculate sign of divisor
    # i.e., sign will be negative
    # either one of them is negative
    # only iff otherwise it will be
    # positive
     
    sign = (-1 if((dividend < 0) ^
                  (divisor < 0)) else 1);
     
    # remove sign of operands
    dividend = abs(dividend);
    divisor = abs(divisor);
     
    # Initialize
    # the quotient
    quotient = 0;
    temp = 0;
     
    # test down from the highest
    # bit and accumulate the
    # tentative value for valid bit
    for i in range(31, -1, -1):
        if (temp + (divisor << i) <= dividend):
            temp += divisor << i;
            quotient |= 1 << i;
     
    return sign * quotient;
 
# Driver code
a = 10;
b = 3;
print(divide(a, b));
 
a = 43;
b = -8;
print(divide(a, b));
 
# This code is contributed by mits


C#
// C# implementation to Divide
// two integers without using
// multiplication, division
// and mod operator
using System;
 
// Function to divide a by b
// and return floor value it
class GFG
{
public static long divide(long dividend,
                          long divisor)
{
 
// Calculate sign of divisor
// i.e., sign will be negative
// only iff either one of them
// is negative otherwise it
// will be positive
long sign = ((dividend < 0) ^
             (divisor < 0)) ? -1 : 1;
 
// remove sign of operands
dividend = Math.Abs(dividend);
divisor = Math.Abs(divisor);
 
// Initialize the quotient
long quotient = 0, temp = 0;
 
// test down from the highest
// bit and accumulate the
// tentative value for
// valid bit
for (int i = 31; i >= 0; --i)
{
 
    if (temp + (divisor << i) <= dividend)
    {
        temp += divisor << i;
        quotient |= 1LL << i;
    }
}
 
return (sign * quotient);
}
 
// Driver code
public static void Main()
{
int a = 10, b = 3;
Console.WriteLine(divide(a, b));
 
int a1 = 43, b1 = -8;
Console.WriteLine(divide(a1, b1));
 
}
}
 
// This code is contributed by mits


PHP
= 0; --$i)
{
 
    if ($temp + ($divisor << $i) <= $dividend)
    {
        $temp += $divisor << $i;
        $quotient |= (double)(1) << $i;
    }
}
 
return $sign * $quotient;
}
 
// Driver code
$a = 10;
$b = 3;
echo divide($a, $b). "\n";
 
$a = 43;
$b = -8;
echo divide($a, $b);
 
// This code is contributed by mits
?>


输出 :

3
-5

时间复杂度: O(a)
辅助空间: O(1)
高效方法:使用位操作以找到商。除数和除数可以写成

由于每个数字都可以以2为底数(0或1)来表示,因此可以使用移位运算符以二进制形式表示商,如下所示:

  1. 确定商中的最高有效位。这可以容易地通过对位位置i迭代从31到1来计算。
  2. 找到第一位divisor << i               小于股息,并继续更新为真的i比特位置。
  3. 将结果添加到temp变量中以检查下一个位置,以使(temp +(除数<< i))小于被除数
  4. 用相应的符号更新后,返回商的最终答案。

下面是上述方法的实现:

C++

// C++ implementation to Divide two
// integers without using multiplication,
// division and mod operator
#include 
using namespace std;
 
// Function to divide a by b and
// return floor value it
int divide(long long dividend, long long divisor) {
 
  // Calculate sign of divisor i.e.,
  // sign will be negative only iff
  // either one of them is negative
  // otherwise it will be positive
  int sign = ((dividend < 0) ^
              (divisor < 0)) ? -1 : 1;
 
  // remove sign of operands
  dividend = abs(dividend);
  divisor = abs(divisor);
 
  // Initialize the quotient
  long long quotient = 0, temp = 0;
 
  // test down from the highest bit and
  // accumulate the tentative value for
  // valid bit
  for (int i = 31; i >= 0; --i) {
 
    if (temp + (divisor << i) <= dividend) {
      temp += divisor << i;
      quotient |= 1LL << i;
    }
  }
 
  return sign * quotient;
}
 
// Driver code
int main() {
  int a = 10, b = 3;
  cout << divide(a, b) << "\n";
 
  a = 43, b = -8;
  cout << divide(a, b);
 
  return 0;
}

Java

// Java implementation to Divide
// two integers without using
// multiplication, division
// and mod operator
import java.io.*;
import java.util.*;
 
// Function to divide a by b
// and return floor value it
class GFG
{
public static long divide(long dividend,
                        long divisor)
{
 
// Calculate sign of divisor
// i.e., sign will be negative
// only iff either one of them
// is negative otherwise it
// will be positive
long sign = ((dividend < 0) ^
            (divisor < 0)) ? -1 : 1;
 
// remove sign of operands
dividend = Math.abs(dividend);
divisor = Math.abs(divisor);
 
// Initialize the quotient
long quotient = 0, temp = 0;
 
// test down from the highest
// bit and accumulate the
// tentative value for
// valid bit
// 1<<31 behaves incorrectly and gives Integer
// Min Value which should not be the case, instead
  // 1L<<31 works correctly.
for (int i = 31; i >= 0; --i)
{
 
    if (temp + (divisor << i) <= dividend)
    {
        temp += divisor << i;
        quotient |= 1L << i;
    }
}
 
return (sign * quotient);
}
 
// Driver code
public static void main(String args[])
{
int a = 10, b = 3;
System.out.println(divide(a, b));
 
int a1 = 43, b1 = -8;
System.out.println(divide(a1, b1));
 
 
}
}
 
// This code is contributed
// by Akanksha Rai(Abby_akku)

Python3

# Python3 implementation to
# Divide two integers
# without using multiplication,
# division and mod operator
 
# Function to divide a by
# b and return floor value it
def divide(dividend, divisor):
     
    # Calculate sign of divisor
    # i.e., sign will be negative
    # either one of them is negative
    # only iff otherwise it will be
    # positive
     
    sign = (-1 if((dividend < 0) ^
                  (divisor < 0)) else 1);
     
    # remove sign of operands
    dividend = abs(dividend);
    divisor = abs(divisor);
     
    # Initialize
    # the quotient
    quotient = 0;
    temp = 0;
     
    # test down from the highest
    # bit and accumulate the
    # tentative value for valid bit
    for i in range(31, -1, -1):
        if (temp + (divisor << i) <= dividend):
            temp += divisor << i;
            quotient |= 1 << i;
     
    return sign * quotient;
 
# Driver code
a = 10;
b = 3;
print(divide(a, b));
 
a = 43;
b = -8;
print(divide(a, b));
 
# This code is contributed by mits

C#

// C# implementation to Divide
// two integers without using
// multiplication, division
// and mod operator
using System;
 
// Function to divide a by b
// and return floor value it
class GFG
{
public static long divide(long dividend,
                          long divisor)
{
 
// Calculate sign of divisor
// i.e., sign will be negative
// only iff either one of them
// is negative otherwise it
// will be positive
long sign = ((dividend < 0) ^
             (divisor < 0)) ? -1 : 1;
 
// remove sign of operands
dividend = Math.Abs(dividend);
divisor = Math.Abs(divisor);
 
// Initialize the quotient
long quotient = 0, temp = 0;
 
// test down from the highest
// bit and accumulate the
// tentative value for
// valid bit
for (int i = 31; i >= 0; --i)
{
 
    if (temp + (divisor << i) <= dividend)
    {
        temp += divisor << i;
        quotient |= 1LL << i;
    }
}
 
return (sign * quotient);
}
 
// Driver code
public static void Main()
{
int a = 10, b = 3;
Console.WriteLine(divide(a, b));
 
int a1 = 43, b1 = -8;
Console.WriteLine(divide(a1, b1));
 
}
}
 
// This code is contributed by mits

的PHP

= 0; --$i)
{
 
    if ($temp + ($divisor << $i) <= $dividend)
    {
        $temp += $divisor << $i;
        $quotient |= (double)(1) << $i;
    }
}
 
return $sign * $quotient;
}
 
// Driver code
$a = 10;
$b = 3;
echo divide($a, $b). "\n";
 
$a = 43;
$b = -8;
echo divide($a, $b);
 
// This code is contributed by mits
?>

输出 :

3
-5

时间复杂度: O(log(a))
辅助空间: O(1)