给定两个正整数n和m 。问题是不使用算术运算运算符检查n是否可被2 m整除。
例子:
Input : n = 8, m = 2
Output : Yes
Input : n = 14, m = 3
Output : No
方法:如果一个数字可被2整除,则其最低有效位(LSB)设置为0,如果被4整除,则两个LSB设置为0,如果被8则将三个LSB设置为0,依此类推。请记住,如果(n&(((1 << m)– 1))等于0,则数字n可以被2 m整除。
C++
// C++ implementation to chech whether n
// is divisible by pow(2, m)
#include
using namespace std;
// function to chech whether n
// is divisible by pow(2, m)
bool isDivBy2PowerM(unsigned int n,
unsigned int m)
{
// if expression results to 0, then
// n is divisible by pow(2, m)
if ((n & ((1 << m) - 1)) == 0)
return true;
// n is not divisible
return false;
}
// Driver program to test above
int main()
{
unsigned int n = 8, m = 2;
if (isDivBy2PowerM(n, m))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
// JAVA Code for Check if n is divisible
// by power of 2 without using arithmetic
// operators
import java.util.*;
class GFG {
// function to chech whether n
// is divisible by pow(2, m)
static boolean isDivBy2PowerM(int n,
int m)
{
// if expression results to 0, then
// n is divisible by pow(2, m)
if ((n & ((1 << m) - 1)) == 0)
return true;
// n is not divisible
return false;
}
/* Driver program to test above function */
public static void main(String[] args)
{
int n = 8, m = 2;
if (isDivBy2PowerM(n, m))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by Arnav Kr. Mandal.
Python3
# Python3 implementation to chech
# whether n is divisible by pow(2, m)
# function to chech whether n
# is divisible by pow(2, m)
def isDivBy2PowerM (n, m):
# if expression results to 0, then
# n is divisible by pow(2, m)
if (n & ((1 << m) - 1)) == 0:
return True
# n is not divisible
return False
# Driver program to test above
n = 8
m = 2
if isDivBy2PowerM(n, m):
print("Yes")
else:
print( "No")
# This code is contributed by "Sharad_Bhardwaj".
C#
// C# Code for Check if n is divisible
// by power of 2 without using arithmetic
// operators
using System;
class GFG {
// function to chech whether n
// is divisible by pow(2, m)
static bool isDivBy2PowerM(int n, int m)
{
// if expression results to 0, then
// n is divisible by pow(2, m)
if ((n & ((1 << m) - 1)) == 0)
return true;
// n is not divisible
return false;
}
/* Driver program to test above function */
public static void Main()
{
int n = 8, m = 2;
if (isDivBy2PowerM(n, m))
Console.Write("Yes");
else
Console.Write("No");
}
}
// This code is contributed by Sam007
PHP
Javascript
输出:
Yes