您将得到一个正整数n作为除数,并得到另一个数字m(2 ^ k的形式),您必须在不进行实际除法的情况下找到商和余数。
例子:
Input : n = 43, m = 8
Output : Quotient = 5, Remainder = 3
Input : n = 58, m = 16
Output : Quotient = 3, Remainder = 10
在此,我们使用数字的按位表示来理解任何数字除以2 ^ k的除数的作用。所有为2的幂的数字在其表示中仅包含1个设置位,我们将使用此属性。
为了找到余数,我们将对除数(n)和除数减1(m-1)进行逻辑与,这将仅将除数的置位权赋予除数的设定位,在这种情况下,除数的设定位就是我们的实际余数。
此外,除数的左部分(从除数中的设置位的位置开始)将被视为商。因此,从除数(n)开始,将所有位从除数的置位位置上移去,将得到商,而将右数对数log2(m)右移将完成寻找商的工作。
- 余数= n&(m-1)
- 商=(n >> log2(m))
注意:Log2(m)将给出m的二进制表示形式中存在的位数。
C++
// CPP to find remainder and quotient
#include
using namespace std;
// function to print remainder and quotient
void divide(int n,int m)
{
// print Remainder by
// n AND (m-1)
cout <<"Remainder = " << ((n) &(m-1));
// print quotient by
// right shifting n by (log2(m)) times
cout <<"\nQuotient = " <<(n >> (int)(log2(m)));
}
// driver program
int main()
{
int n = 43, m = 8;
divide(n, m);
return 0;
}
Java
// Java to find remainder and quotient
import java.io.*;
public class GFG {
// function to print remainder and
// quotient
static void divide(int n, int m)
{
// print Remainder by
// n AND (m-1)
System.out.println("Remainder = "
+ ((n) &(m-1)));
// print quotient by right shifting
// n by (log2(m)) times
System.out.println("Quotient = "
+ (n >> (int)(Math.log(m) / Math.log(2))));
}
// driver program
static public void main (String[] args)
{
int n = 43, m = 8;
divide(n, m);
}
}
// This code is contributed by vt_m.
Python 3
# Python 3 to find remainder and
# quotient
import math
# function to print remainder and
# quotient
def divide(n, m):
# print Remainder by
# n AND (m-1)
print("Remainder = ",
((n) &(m-1)))
# print quotient by
# right shifting n by
# (log2(m)) times
print("Quotient = " ,(n >>
(int)(math.log2(m))))
# driver program
n = 43
m = 8
divide(n, m)
# This code is contributed by
# Smitha
C#
// C# to find remainder and quotient
using System;
public class GFG
{
// function to print remainder and quotient
static void divide(int n,int m)
{
// print Remainder by
// n AND (m-1)
Console.WriteLine("Remainder = " +((n) & (m - 1)));
// print quotient by
// right shifting n by (log2(m)) times
Console.WriteLine("Quotient = "
+ (n >> (int)(Math.Log(m))));
}
// Driver program
static public void Main ()
{
int n = 43, m = 8;
divide(n, m);
}
}
// This code is contributed by vt_m.
PHP
> (int)(log($m, 2)));
}
// Driver Code
$n = 43;
$m = 8;
divide($n, $m);
//This code is contributed by mits
?>
Javascript
输出:
Remainder = 3
Quotient = 5