So using sieve I calculate the factors of each number, then I calculated the sum of all the factors for all elements, stored then in a hash table.
And answered all the queries using a single look up.
Here is my code:
#include <bits/stdc++.h>
using namespace std;
#define MX 10000
#define ll long long
#define endl "\n"
vector<int> factorSumIndex(MX+1,-1);
ll Pow(ll a, int b){
ll ans = 1;
while(b>0){
if(b&1){
ans = ans *a;
}
a = a*a;
b = b>>1;
}
return ans;
}
void init(){
vector<vector<pair<int,int> > > factors(MX+1);
vector<int> sieve(MX+1);
for(int i=1;i<=MX;i++){
sieve[i] = i;
}
for(int i=2;i<=MX;i++){
if(sieve[i] == i){
factors[i].push_back(make_pair(i,1));
for(int j = i+i;j<=MX;j+=i){
int cnt = 0;
while(sieve[j]%i == 0){
sieve[j]/=i; cnt++;
}
factors[j].push_back(make_pair(i,cnt));
}
}
}
for(int i=1;i<=MX;i++){
ll sum = 1;
vector<pair<int,int> > &factor = factors[i];
for(int j=0;j<factor.size();j++){
sum = sum * ( (Pow(factor[j].first,factor[j].second+1) - 1) / (factor[j].first - 1) );
}
if(sum<=MX){
factorSumIndex[sum] = i;
}
}
}
int main(){
init();
int num;
cin>>num;
while(num!=0){
cout<<factorSumIndex[num]<<endl;
cin>>num;
}
return 0;
}