Given an integer N., The task is to find the number of distinct permutations of length N, such that the bitwise AND value of each permutation is zero.
Examples:
Input: N = 1
Output: 0
Explanation: There is only one permutation of length 1: [1] and it’s bitwise AND is 1 .
Input: N = 3
Output: 6
Explanation: Permutations of length N having bitwise AND as 0 are : [1, 2, 3], [1, 3, 2], [2, 1, 3], [3, 1, 2], [2, 3, 1], [3, 2, 1] .
Approach: The task can be solved using observations. One can observe that if a number is a power of 2, let’s say ‘x‘, bitwise AND of x & (x-1) is always zero. All permutations of length greater than 1, have bitwise AND as zero, and for N = 1, the count of distinct permutations is 0. Therefore, the required count is equal to the number of possible permutations i.e N!
Below is the implementation of the above approach –
C++
#include <bits/stdc++.h>
using namespace std;
long long int fact( long long N)
{
long long int ans = 1;
for ( int i = 2; i <= N; i++)
ans *= i;
return ans;
}
long long permutation_count( long long n)
{
if (n == 1)
return 0;
return fact(n);
}
int main()
{
long long N = 3;
cout << permutation_count(N);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static long fact( long N)
{
long ans = 1 ;
for ( int i = 2 ; i <= N; i++)
ans *= i;
return ans;
}
static long permutation_count( long n)
{
if (n == 1 )
return 0 ;
return fact(n);
}
public static void main (String[] args) {
long N = 3 ;
System.out.println(permutation_count(N));
}
}
|
Python3
def fact(N):
ans = 1
for i in range ( 2 , N + 1 ):
ans * = i
return ans
def permutation_count(n):
if (n = = 1 ):
return 0
return fact(n)
if __name__ = = "__main__" :
N = 3
print (permutation_count(N))
|
C#
using System;
class GFG
{
static long fact( long N)
{
long ans = 1;
for ( int i = 2; i <= N; i++)
ans *= i;
return ans;
}
static long permutation_count( long n)
{
if (n == 1)
return 0;
return fact(n);
}
public static void Main()
{
long N = 3;
Console.Write(permutation_count(N));
}
}
|
Javascript
<script>
function fact(N)
{
let ans = 1;
for (let i = 2; i <= N; i++)
ans *= i;
return ans;
}
function permutation_count(n)
{
if (n == 1)
return 0;
return fact(n);
}
let N = 3;
document.write(permutation_count(N));
</script>
|
Time complexity: O(N)
Auxiliary Space: O(1)