question:https://codility.com/programmers/lessons/9
To solve this question , I get each element's divsors which appearing in input Array A using Sieve of Eratosthenes method. Time complexity is O(nlogn);
Then we iterate array A to get the ith non-divsors by A.size() - count(element) for element in divsor[A[i]] in divsors. Time complexity is O(n*?
); ?
represent the average of divsors
this method unsatisfy the time requirement , for two test case get TIMEOUT error. NEED IMPROVE IT LATER.
code:
#include <algorithm> #include <map> //this method not fast enough vector<int> solution(vector<int> &A) { // write your code in C++11 map<int,int> dic; map<int,vector<int> > divsors; int size = A.size(); int max = *max_element(A.begin(),A.end()); for(int i=0; i<size; i++){ dic[A[i]]++; if(divsors.count(A[i])==0){ vector<int> vec(1,1); divsors.insert(make_pair(A[i],vec)); } } for(int i=2; i<= max; i++){ int element = i; while(element <=max){ if(divsors.count(element)!=0 && find(divsors[element].begin(),divsors[element].end(),i)==divsors[element].end()){ divsors[element].push_back(i); } element+=i; } } vector<int > res; for(int i=0; i<size; i++){ vector<int> t = divsors[A[i]]; int cnt = size; for(int j=0; j<t.size(); j++){ cnt -= dic[t[j]]; } res.push_back(cnt); } return res; }