Количество пар с побитовым ИЛИ как нечетное число

Опубликовано: 5 Января, 2022

Дан массив A [] размера N. Задача состоит в том, чтобы найти, сколько пар (i, j) существует таких, что A [i] OR A [j] нечетно.
Примеры :

 Ввод : N = 4
            A [] = {5, 6, 2, 8}
Выход : 3
Пояснение :
Поскольку пара A [] = (5, 6), (5, 2), (5, 8),
(6, 2), (6, 8), (2, 8)
5 ИЛИ 6 = 7, 5 ИЛИ 2 = 7, 5 ИЛИ 8 = 13
6 ИЛИ 2 = 6, 6 ИЛИ 8 = 14, 2 ИЛИ 8 = 10
Всего пара A (i, j) = 6 и Odd = 3

Ввод : N = 7
            A [] = {8, 6, 2, 7, 3, 4, 9}
Выход : 15

Рекомендуется: сначала попробуйте свой подход в {IDE}, прежде чем переходить к решению.

Простое решение - проверить каждую пару и найти побитовое ИЛИ и посчитать все такие пары с побитовым ИЛИ как нечетные.
Ниже представлена реализация описанного выше подхода:

C ++

// C++ program to count pairs with odd OR
#include <iostream>
using namespace std;
// Function to count pairs with odd OR
int findOddPair( int A[], int N)
{
int oddPair = 0;
for ( int i = 0; i < N; i++) {
for ( int j = i + 1; j < N; j++) {
// find OR operation
// check odd or odd
if ((A[i] | A[j]) % 2 != 0)
oddPair++;
}
}
// return count of odd pair
return oddPair;
}
// Driver Code
int main()
{
int A[] = { 5, 6, 2, 8 };
int N = sizeof (A) / sizeof (A[0]);
cout << findOddPair(A, N) << endl;
return 0;
}

Джава

// Java program to count pairs
// with odd OR
class GFG
{
// Function to count pairs with odd OR
static int findOddPair( int A[], int N)
{
int oddPair = 0 ;
for ( int i = 0 ; i < N; i++)
{
for ( int j = i + 1 ; j < N; j++)
{
// find OR operation
// check odd or odd
if ((A[i] | A[j]) % 2 != 0 )
oddPair++;
}
}
// return count of odd pair
return oddPair;
}
// Driver Code
public static void main(String []args)
{
int A[] = { 5 , 6 , 2 , 8 };
int N = A.length;
System.out.println(findOddPair(A, N));
}
}
// This code is contributed by ANKITRAI1

Python3

# Python3 program to count pairs with odd OR
# Function to count pairs with odd OR
def findOddPair(A, N):
oddPair = 0
for i in range ( 0 , N):
for j in range (i + 1 , N):
# find OR operation
# check odd or odd
if ((A[i] | A[j]) % 2 ! = 0 ):
oddPair + = 1
# return count of odd pair
return oddPair
# Driver Code
def main():
A = [ 5 , 6 , 2 , 8 ]
N = len (A)
print (findOddPair(A, N))
if __name__ = = '__main__' :
main()
# This code is contributed by PrinciRaj1992

C #

// C# program to count pairs
// with odd OR
using System;
public class GFG{
// Function to count pairs with odd OR
static int findOddPair( int [] A, int N)
{
int oddPair = 0;
for ( int i = 0; i < N; i++)
{
for ( int j = i + 1; j < N; j++)
{
// find OR operation
// check odd or odd
if ((A[i] | A[j]) % 2 != 0)
oddPair++;
}
}
// return count of odd pair
return oddPair;
}
// Driver Code
static public void Main (){
int []A = { 5, 6, 2, 8 };
int N = A.Length;
Console.WriteLine(findOddPair(A, N));
}
}
//This code is contributed by ajit

PHP

<?php
//PHP program to count pairs with odd OR
// Function to count pairs with odd OR
function findOddPair( $A , $N )
{
$oddPair = 0;
for ( $i = 0; $i < $N ; $i ++) {
for ( $j = $i + 1; $j < $N ; $j ++) {
// find OR operation
// check odd or odd
if (( $A [ $i ] | $A [ $j ]) % 2 != 0)
$oddPair ++;
}
}
// return count of odd pair
return $oddPair ;
}
// Driver Code
$A = array (5, 6, 2, 8 );
$N = sizeof( $A ) / sizeof( $A [0]);
echo findOddPair( $A , $N ), " " ;
#This code is contributed by ajit
?>

Javascript

<script>
// Javascript program to count pairs with odd OR
// Function to count pairs with odd OR
function findOddPair(A, N)
{
let oddPair = 0;
for (let i = 0; i < N; i++)
{
for (let j = i + 1; j < N; j++)
{
// find OR operation
// check odd or odd
if ((A[i] | A[j]) % 2 != 0)
oddPair++;
}
}
// return count of odd pair
return oddPair;
}
// Driver Code
let A = [ 5, 6, 2, 8 ];
let N = A.length;
document.write(findOddPair(A, N));
// This code is contributed by souravmahato348.
</script>
Выход:
 3

Сложность времени : O (N 2 )
Эффективное решение - подсчитать пары с четным ИЛИ и вычесть их из общего количества пар, чтобы получить пары с нечетным побитовым ИЛИ. Для этого подсчитайте числа с последним битом как 0. Тогда количество пар с четным побитовым ИЛИ = count * (count - 1) / 2 и общее количество пар будет N * (N-1) / 2.
Следовательно, пары с ODD Bitwise-OR будут:

Total Pairs - Pairs with EVEN Bitwise-OR

Ниже представлена реализация описанного выше подхода:

C ++

// C++ program to count pairs with odd OR
#include <iostream>
using namespace std;
// Function to count pairs with odd OR
int countOddPair( int A[], int N)
{
// Count total even numbers in
// array
int count = 0;
for ( int i = 0; i < N; i++)
if (!(A[i] & 1))
count++;
// Even pair count
int evenPairCount = count * (count - 1) / 2;
// Total pairs
int totPairs = N * (N - 1) / 2;
// Return Odd pair count
return totPairs - evenPairCount;
}
// Driver main
int main()
{
int A[] = { 5, 6, 2, 8 };
int N = sizeof (A) / sizeof (A[0]);
cout << countOddPair(A, N) << endl;
return 0;
}

Джава

// Java program to count pairs with odd OR
public class GFG {
// Function to count pairs with odd OR
static int countOddPair( int A[], int N) {
// Count total even numbers in
// array
int count = 0 ;
for ( int i = 0 ; i < N; i++) {
if ((A[i] % 2 != 1 )) {
count++;
}
}
// Even pair count
int evenPairCount = count * (count - 1 ) / 2 ;
// Total pairs
int totPairs = N * (N - 1 ) / 2 ;
// Return Odd pair count
return totPairs - evenPairCount;
}
// Driver main
public static void main(String[] args) {
int A[] = { 5 , 6 , 2 , 8 };
int N = A.length;
System.out.println(countOddPair(A, N));
}
}

Python3

# Python 3program to count pairs with odd OR
# Function to count pairs with odd OR
def countOddPair(A, N):
# Count total even numbers in
# array
count = 0
for i in range ( 0 , N):
if (A[i] % 2 ! = 1 ):
count + = 1
# Even pair count
evenPairCount = count * (count - 1 ) / 2
# Total pairs
totPairs = N * (N - 1 ) / 2
# Return Odd pair count
return ( int )(totPairs - evenPairCount)
# Driver Code
A = [ 5 , 6 , 2 , 8 ]
N = len (A)
print (countOddPair(A, N))
# This code is contributed by PrinciRaj1992

C #

// C# program to count pairs with odd OR
using System;
public class GFG {
// Function to count pairs with odd OR
static int countOddPair( int []A, int N) {
// Count total even numbers in
// array
int count = 0;
for ( int i = 0; i < N; i++) {
if ((A[i] % 2 != 1)) {
count++;
}
}
// Even pair count
int evenPairCount = count * (count - 1) / 2;
// Total pairs
int totPairs = N * (N - 1) / 2;
// Return Odd pair count
return totPairs - evenPairCount;
}
// Driver main
public static void Main() {
int []A = {5, 6, 2, 8};
int N = A.Length;
Console.WriteLine(countOddPair(A, N));
}
}
/*This code is contributed by PrinciRaj1992*/

PHP

<?php
// PHP program to count pairs with odd OR
// Function to count pairs with odd OR
function countOddPair( $A , $N )
{
// Count total even numbers
// in array
$count = 0;
for ( $i = 0; $i < $N ; $i ++)
if (!( $A [ $i ] & 1))
$count ++;
// Even pair count
$evenPairCount = $count *
( $count - 1) / 2;
// Total pairs
$totPairs = $N * ( $N - 1) / 2;
// Return Odd pair count
return ( $totPairs - $evenPairCount );
}
// Driver main
$A = array ( 5, 6, 2, 8 );
$N = sizeof( $A );
echo countOddPair( $A , $N ), " " ;
// This code is contributed by Sach_Code
?>

Javascript

<script>
// Javascript program to count
// pairs with odd OR
// Function to count pairs with odd OR
function countOddPair(A, N)
{
// Count total even numbers in
// array
let count = 0;
for (let i = 0; i < N; i++)
if (!(A[i] & 1))
count++;
// Even pair count
let evenPairCount =
parseInt(count * (count - 1) / 2);
// Total pairs
let totPairs = parseInt(N * (N - 1) / 2);
// Return Odd pair count
return totPairs - evenPairCount;
}
// Driver main
let A = [ 5, 6, 2, 8 ];
let N = A.length;
document.write(countOddPair(A, N));
</script>
Выход:
 3

Сложность времени : O (N)

Вниманию читателя! Не прекращайте учиться сейчас. Освойте все важные концепции DSA с помощью самостоятельного курса DSA по приемлемой для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .

Если вы хотите посещать живые занятия с отраслевыми экспертами, пожалуйста, обращайтесь к Geeks Classes Live и Geeks Classes Live USA.