Bitwise AND of all the odd numbers from 1 to N
Last Updated :
05 May, 2021
Given an integer N, the task is to find the bitwise AND (&) of all the odd integers from the range [1, N].
Examples:
Input: N = 7
Output: 1
(1 & 3 & 5 & 7) = 1
Input: N = 1
Output: 1
Naive approach: Starting from 1, bitwise AND all the odd numbers ? N.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
int bitwiseAndOdd( int n)
{
int result = 1;
for ( int i = 3; i <= n; i = i + 2) {
result = (result & i);
}
return result;
}
int main()
{
int n = 10;
cout << bitwiseAndOdd(n);
return 0;
}
|
Java
class GFG
{
static int bitwiseAndOdd( int n)
{
int result = 1 ;
for ( int i = 3 ; i <= n; i = i + 2 )
{
result = (result & i);
}
return result;
}
public static void main (String[] args)
{
int n = 10 ;
System.out.println(bitwiseAndOdd(n));
}
}
|
Python3
def bitwiseAndOdd(n) :
result = 1 ;
for i in range ( 3 , n + 1 , 2 ) :
result = (result & i);
return result;
if __name__ = = "__main__" :
n = 10 ;
print (bitwiseAndOdd(n));
|
C#
using System;
class GFG
{
static int bitwiseAndOdd( int n)
{
int result = 1;
for ( int i = 3; i <= n; i = i + 2)
{
result = (result & i);
}
return result;
}
public static void Main()
{
int n = 10;
Console.WriteLine(bitwiseAndOdd(n));
}
}
|
Javascript
<script>
function bitwiseAndOdd(n)
{
var result = 1;
for ( var i = 3; i <= n; i = i + 2)
{
result = (result & i);
}
return result;
}
var n = 10;
document.write(bitwiseAndOdd(n));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Efficient approach: Bitwise AND with 1 will always give 1 as the result if the integer has a one at the least significant bit (all the odd integers in this case). So, the result will be 1 in all the cases.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
int bitwiseAndOdd( int n)
{
return 1;
}
int main()
{
int n = 10;
cout << bitwiseAndOdd(n);
return 0;
}
|
Java
class GFG
{
static int bitwiseAndOdd( int n)
{
return 1 ;
}
public static void main (String[] args)
{
int n = 10 ;
System.out.println(bitwiseAndOdd(n));
}
}
|
Python 3
def bitwiseAndOdd(n):
return 1
n = 10
print (bitwiseAndOdd(n))
|
C#
using System;
class GFG
{
static int bitwiseAndOdd( int n)
{
return 1;
}
public static void Main()
{
int n = 10;
Console.WriteLine(bitwiseAndOdd(n));
}
}
|
Javascript
<script>
function bitwiseAndOdd(n)
{
return 1;
}
var n = 10;
document.write( bitwiseAndOdd(n));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...