Given an array arr[] comprising of n non-zero, positive integers and an integer x, find the bitwise OR of all multiples of x present in the array.
The result of OR operation should be in decimal form. If no multiple of x is found, the answer should be 0.
Examples:
Input: arr[] = [3, 4, 3, 9], x = 2
Output: 4
Explanation: Only multiple of 2 in array is 4.Input: arr[] = [9, 3, 1, 6, 1], x = 3
Output: 15
Explanation: Multiples of 3 in array are 9, 3 and 6. Their OR value is 15.
Try It Yourself
Using Bitwise OR - O(n) Time and O(1) Space
The idea is to traverse the array and consider only those elements that are divisible by x.
- Initialize ans as 0.
- For each element arr[i], check whether it is a multiple of x using: arr[i] % x == 0
- If it is a multiple of x, include it in the result using bitwise OR: ans = ans | arr[i]
- After traversing the entire array, ans contains the bitwise OR of all multiples of x.
- If no element is a multiple of x, ans remains 0, which is the required result.
Consider: arr[] = [9, 3, 1, 6, 1] and x = 3.
- Initialize ans = 0 and traverse the array from left to right.
- For 9, 9 % 3 == 0, so include it in the result: ans = 0 | 9 = 9
- For 3, 3 % 3 == 0, so include it: ans = 9 | 3 = 11
- For 1, 1 % 3 != 0, so skip it.
- For 6, 6 % 3 == 0, so include it: ans = 11 | 6 = 15
- For 1, 1 % 3 != 0, so skip it.
After processing all elements, ans becomes 15.
Therefore, the bitwise OR of all elements that are multiples of 3 is 15.
#include <bits/stdc++.h>
using namespace std;
int findOR(vector<int>& arr, int x) {
int ans = 0;
// Traverse the array and OR all elements that are divisible by x.
for (int num : arr) {
if (num % x == 0)
ans |= num;
}
return ans;
}
int main() {
vector<int> arr = {9, 3, 1, 6, 1};
int x = 3;
cout << findOR(arr, x);
return 0;
}
class GFG {
public static int findOR(int[] arr, int x) {
int ans = 0;
// Traverse the array and OR all elements that are divisible by x.
for (int num : arr) {
if (num % x == 0)
ans |= num;
}
return ans;
}
public static void main(String[] args) {
int[] arr = {9, 3, 1, 6, 1};
int x = 3;
System.out.println(findOR(arr, x));
}
}
def findOR(arr, x):
ans = 0
# Traverse the array and OR all elements that are divisible by x.
for num in arr:
if num % x == 0:
ans |= num
return ans
if __name__ == "__main__":
arr = [9, 3, 1, 6, 1]
x = 3
print(findOR(arr, x))
using System;
class GFG {
static int findOR(int[] arr, int x) {
int ans = 0;
// Traverse the array and OR all elements that are divisible by x.
foreach (int num in arr) {
if (num % x == 0)
ans |= num;
}
return ans;
}
static void Main() {
int[] arr = {9, 3, 1, 6, 1};
int x = 3;
Console.WriteLine(findOR(arr, x));
}
}
function findOR(arr, x) {
let ans = 0;
// Traverse the array and OR all elements that are divisible by x.
for (let num of arr) {
if (num % x === 0)
ans |= num;
}
return ans;
}
// Driver code
let arr = [9, 3, 1, 6, 1];
let x = 3;
console.log(findOR(arr, x));
Output
15