Skip to content

Commit 629ba91

Browse files
committed
Added two new Algorithms in Bit Manipulation and Number Theory
1 parent 48cf351 commit 629ba91

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// This algorithm finds unique Bitwise OR of
2+
// all the subarrays of an array.
3+
// The Time Complexity might look like
4+
// its O(n^2), but upon taking a closer look
5+
// at algorithm, it comes out to be of the
6+
// order of O(n)
7+
#include <bits/stdc++.h>
8+
using namespace std;
9+
10+
int subarrayBitwiseORs(vector<int>& A) {
11+
unordered_set<int> st;
12+
int n = A.size(), chk = 0, curr;
13+
for(int i = n - 1; i >= 0; i--) {
14+
curr = A[i];
15+
st.insert(curr);
16+
chk = 0;
17+
for(int j = i + 1; j < n && chk != curr; j++) {
18+
curr |= A[j];
19+
chk |= A[j];
20+
st.insert(curr);
21+
}
22+
}
23+
return st.size();
24+
}
25+
26+
int main() {
27+
int n;
28+
cin >> n;
29+
vector<int> arr(n);
30+
for(int i = 0; i < n; i++) {
31+
cin >> arr[i];
32+
}
33+
cout << subarrayBitwiseORs(arr) << endl;
34+
return 0;
35+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// This code will have a complexity of O(log b), but
2+
// we can use __int128 in C++ to avoid any potential
3+
// overflows and work in O(1).
4+
#include <bits/stdc++.h>
5+
using namespace std;
6+
typedef long long ll;
7+
8+
ll binaryMultiplication(ll a, ll b) {
9+
ll x = 0, y = a;
10+
while (b > 0) {
11+
if (b & 1)
12+
x = (x + y);
13+
y = (y + y);
14+
b >>= 1;
15+
}
16+
return x;
17+
}
18+
19+
int main() {
20+
ll a, b;
21+
cin >> a >> b;
22+
// Finding a^b
23+
cout << binaryMultiplication(a, b) << endl;
24+
return 0;
25+
}

0 commit comments

Comments
 (0)