Bitwise AND of all even number up to N
Last Updated :
28 Dec, 2022
Given an integer N, the task is to find bitwise and (&) of all even numbers from 1 to N.
Examples:
Input: 2
Output: 2
Input :10
Output : 0
Explanation: Bitwise and of 2, 4, 6, 8 and 10 are 0.
Naive approach: Initialize result as 2. Iterate the loop from 4 to n (for all even numbers) and update the result by finding bitwise and (&).
Below is the implementation of the approach:
C++
#include <iostream>
using namespace std;
int bitwiseAndTillN( int n)
{
int result = 2;
for ( int i = 4; i <= n; i = i + 2) {
result = result & i;
}
return result;
}
int main()
{
int n = 2;
cout << bitwiseAndTillN(n);
return 0;
}
|
Java
class GFG
{
static int bitwiseAndTillN( int n)
{
int result = 2 ;
for ( int i = 4 ; i <= n; i = i + 2 )
{
result = result & i;
}
return result;
}
public static void main (String[] args)
{
int n = 2 ;
System.out.println(bitwiseAndTillN(n));
}
}
|
Python3
def bitwiseAndTillN(n) :
result = 2 ;
for i in range ( 4 , n + 1 , 2 ) :
result = result & i;
return result;
if __name__ = = "__main__" :
n = 2 ;
print (bitwiseAndTillN(n));
|
C#
using System;
class GFG
{
static int bitwiseAndTillN( int n)
{
int result = 2;
for ( int i = 4; i <= n; i = i + 2)
{
result = result & i;
}
return result;
}
public static void Main()
{
int n = 2;
Console.WriteLine(bitwiseAndTillN(n));
}
}
|
Javascript
<script>
function bitwiseAndTillN(n) {
let result = 2;
for (let i = 4; i <= n; i = i + 2) {
result = result & i;
}
return result;
}
let n = 2;
document.write(bitwiseAndTillN(n));
</script>
|
Time Complexity: O(n), where n is the given integer.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Efficient approach: Efficient approach is to return 2 for N less than 4 and return 0 for all N>=4 because bitwise and of 2 and 4 is 0 and bitwise and of 0 with any number is 0.
Below is the implementation of the approach:
C++
#include <iostream>
using namespace std;
int bitwiseAndTillN( int n)
{
if (n < 4)
return 2;
else
return 0;
}
int main()
{
int n = 2;
cout << bitwiseAndTillN(n);
return 0;
}
|
Java
class GFG
{
static int bitwiseAndTillN( int n)
{
if (n < 4 )
return 2 ;
else
return 0 ;
}
public static void main (String[] args)
{
int n = 2 ;
System.out.println(bitwiseAndTillN(n));
}
}
|
Python3
def bitwiseAndTillN( n):
if (n < 4 ):
return 2
else :
return 0
n = 2
print (bitwiseAndTillN(n))
|
C#
using System;
class GFG
{
static int bitwiseAndTillN( int n)
{
if (n < 4)
return 2;
else
return 0;
}
public static void Main()
{
int n = 2;
Console.WriteLine(bitwiseAndTillN(n));
}
}
|
Javascript
<script>
function bitwiseAndTillN(n)
{
if (n < 4)
return 2;
else
return 0;
}
let n = 2;
document.write (bitwiseAndTillN(n));
</script>
|
Time complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...