Given 3 integers A, B, and N the task is to perform alternate AND-OR operations on A and B, and then assign the result of each operation to A. Find the final value of A
Input: A = 4, B = 5, N = 1
Output: 4
Explanation: Perform 1 operation i.e A = A & B, therefore A = 4 & 5 = 4
Input: A = 4, B = 5, N = 1000
Output: 5
Naive Approach : The task can be solved using observations. It can be observed that the answer will be A AND B If the Number N is Odd. The answer will be A OR B if the Number N is Even. It is because the AND-OR operation is running alternatively.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
int A = 4;
int B = 5;
int n = 1000;
int N = 1;
for (N = 1; N <= n; N++) {
if ((N % 2) != 0) {
A = A & B;
}
else {
A = A | B;
}
}
cout << "Output is:" << A;
return 0;
}
|
Java
import java.io.*;
class GFG {
public static void main (String[] args) {
int A= 4 ;
int B= 5 ;
int n = 1000 ;
int N = 1 ;
for (N= 1 ;N<=n;N++)
{
if ((N % 2 ) != 0 ) {
A = A & B;
} else {
A = A | B;
}}
System.out.println( "Output is:" + A);
}
}
|
Python3
A = 4
B = 5
n = 1000
N = 1
for N in range ( 1 , n + 1 ):
if ((N % 2 ) ! = 0 ):
A = A & B
else :
A = A | B
print ( "Output is:" , end = "")
print (A)
|
C#
using System;
class GFG {
public static void Main()
{
int A=4;
int B=5;
int n =1000;
int N = 1;
for (N=1;N<=n;N++)
{
if ((N % 2) != 0) {
A = A & B;
} else {
A = A | B;
}}
Console.Write( "Output is:" + A);
}
}
|
Javascript
<script>
var A = 4;
var B = 5;
var n = 1000;
var N = 1;
for (N = 1; N <= n; N++) {
if ((N % 2) != 0) {
A = A & B;
} else {
A = A | B;
}
}
document.write( "Output is:" + A);
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Approach: The task can be solved using observations. It can be observed that the answer will be A, only when N is 1, for the rest of the N values, the answer will be B. It is because, after the first operation, both numbers will become equal to B
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int find( int A, int B, int N)
{
if (N == 1)
return A & B;
else
return B;
}
int main()
{
cout << find(4, 5, 1000);
return 0;
}
|
Java
import java.util.*;
class GFG
{
public static int find( int A, int B, int N)
{
if (N == 1 )
return A & B;
else
return B;
}
public static void main(String[] args)
{
System.out.print(find( 4 , 5 , 1000 ));
}
}
|
Python3
def find(A, B, N):
if (N = = 1 ):
return A & B;
else :
return B;
print (find( 4 , 5 , 1000 ));
|
C#
using System;
class GFG
{
static int find( int A, int B, int N)
{
if (N == 1)
return A & B;
else
return B;
}
public static void Main()
{
Console.Write(find(4, 5, 1000));
}
}
|
Javascript
<script>
function find(A, B, N) {
if (N == 1)
return A & B;
else
return B;
}
document.write(find(4, 5, 1000));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Contact Us