Number of special pairs possible from the given two numbers
Given two numbers A, B. The task is to find the numbers of special pairs of A, B. A special pair of two numbers A, B is a pair of numbers X, Y which satisfies both of the given conditions – A = X | Y, B = X & Y.
Examples:
Input: A = 3, B = 0
Output: 2
(0, 3), (1, 2) will satisfy the conditions
Input: A = 5, B = 7
Output: 0
Approach: The key observation here is that if we want the OR of two numbers, X, Y to be equal to A. Then both X, Y has to be less than or equal to A. If anyone is greater A then there OR won’t be equal to A. This will give us the limits where our loop will terminate, rest we will try and check if two pairs meet the given condition, then we will increment the counter.
Below is the required implementation:
C++
#include <iostream>
using namespace std;
int countPairs( int A, int B)
{
int cnt = 0;
for ( int i = 0; i <= A; ++i) {
for ( int j = i; j <= A; ++j) {
int AND = i & j;
int OR = i | j;
if (OR == A and AND == B) {
cnt++;
}
}
}
return cnt;
}
int main()
{
int A = 3, B = 0;
cout << countPairs(A, B);
return 0;
}
|
Java
class GFG
{
static int countPairs( int A, int B)
{
int cnt = 0 ;
for ( int i = 0 ; i <= A; ++i)
{
for ( int j = i; j <= A; ++j)
{
int AND = i & j;
int OR = i | j;
if (OR == A && AND == B)
{
cnt++;
}
}
}
return cnt;
}
public static void main(String [] args)
{
int A = 3 , B = 0 ;
System.out.println(countPairs(A, B));
}
}
|
Python3
def countPairs(A,B):
cnt = 0
for i in range ( 0 ,A + 1 ):
for j in range (i,A + 1 ):
AND = i&j
OR = i|j
if (OR = = A and AND = = B):
cnt + = 1
return cnt
if __name__ = = '__main__' :
A = 3
B = 0
print (countPairs(A,B))
|
C#
using System;
class GFG
{
static int countPairs( int A, int B)
{
int cnt = 0;
for ( int i = 0; i <= A; ++i)
{
for ( int j = i; j <= A; ++j)
{
int AND = i & j;
int OR = i | j;
if (OR == A && AND == B)
{
cnt++;
}
}
}
return cnt;
}
public static void Main()
{
int A = 3, B = 0;
Console.WriteLine(countPairs(A, B));
}
}
|
PHP
<?php
function countPairs( $A , $B )
{
$cnt = 0;
for ( $i = 0; $i <= $A ; ++ $i )
{
for ( $j = $i ; $j <= $A ; ++ $j )
{
$AND = $i & $j ;
$OR = $i | $j ;
if ( $OR == $A && $AND == $B )
{
$cnt ++;
}
}
}
return $cnt ;
}
$A = 3;
$B = 0;
echo countPairs( $A , $B );
?>
|
Javascript
<script>
function countPairs(A, B) {
let cnt = 0;
for (let i = 0; i <= A; ++i) {
for (let j = i; j <= A; ++j) {
let AND = i & j;
let OR = i | j;
if (OR == A && AND == B) {
cnt++;
}
}
}
return cnt;
}
let A = 3, B = 0;
document.write(countPairs(A, B));
<script>
|
Time Complexity: O(A2)
Auxiliary Space: O(1)
Last Updated :
23 Nov, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...