Input Array: int A={2,3,4,5,6} , array is not always sorted.
output Array:{2,1,1,0,2}
- since we can see
A[0]can divide 4 & 6 so it has output 2. A[1]can divide only 6 ,it has output 1.A[2]is divided by 2,so has output 1.A[3]is not able to divide or being divided so has output 0.A[4]is being divided by 2 & 3,so has output 2.
I'm able to solve it using brute force approach which has time complexity of o(n*n). what could be the most efficient way to solve it. thank you. my code:
#include<iostream>
#include<vector>
using namespace std;
//Function to return output vector
vector<int>solve(vector<int> &A) {
vector<int>v;
for(int i=0;i<A.size();i++){
int count=0;
for(int j=0;j<A.size();j++){
if(i!=j){
if(A[j]%A[i]==0 || A[i]%A[j]==0){
count++;
}
}
}
v.push_back(count);
}
return v;
}
int main(){
vector<int>v={2,3,4,5,6};
vector<int>s;
s=solve(v);
//printing the output array
for(int i=0;i<s.size();i++){
cout<<s[i]<<" ";
}
}