Given a number n, check if it is divisible by 8 using bitwise operators.
Examples:
Input : 16
Output :YES
Input :15
Output :NO
Approach: Result = (((n >> 3) << 3) == n). First we shift the 3 bit right then we shift the 3 bit left and then compare the number with the given number if the number is equal to the number then it is the divisible by 8 .
Explanation:
Example: n = 16 given so binary of the 16 is 10000 now we shift the 3 bit right, now we have 00010 so again we shift the 3 bit left, then we have 10000 now compare with the given number first 16==16 in binary so it true so the number is divisible by 8.
CPP
#include <bits/stdc++.h>
using namespace std;
int Div_by_8( int n)
{
return (((n >> 3) << 3) == n);
}
int main()
{
int n = 16;
if (Div_by_8(n))
cout << "YES" << endl;
else
cout << "NO" << endl;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG
{
static boolean Div_by_8( int n)
{
return (((n >> 3 ) << 3 ) == n);
}
public static void main (String[] args)
{
int n = 16 ;
if (Div_by_8(n))
System.out.println( "YES" );
else
System.out.println( "NO" );
}
}
|
Python3
import math
def Div_by_8(n):
return (((n >> 3 ) << 3 ) = = n)
n = 16
if (Div_by_8(n)):
print ( "YES" )
else :
print ( "NO" )
|
C#
using System;
class GFG {
static bool Div_by_8( int n)
{
return (((n >> 3) << 3) == n);
}
public static void Main ()
{
int n = 16;
if (Div_by_8(n))
Console.WriteLine( "YES" );
else
Console.WriteLine( "NO" );
}
}
|
PHP
<?php
function Div_by_8( $n )
{
return ((( $n >> 3) << 3) == $n );
}
$n = 16;
if (Div_by_8( $n ))
echo "YES" ;
else
echo "NO" ;
?>
|
Javascript
<script>
function Div_by_8(n)
{
return (((n >> 3) << 3) == n);
}
var n = 16;
if (Div_by_8(n))
document.write( "YES" );
else
document.write( "NO" );
</script>
|
YES
Time Complexity : O(1)
Space Complexity : O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
31 May, 2022
Like Article
Save Article