题解:P16138 位的方程(popcount)

· · 题解

这个东西的性质很好,首先 \operatorname{popcount} 的取值范围就很好,并且对于每个值都可以唯一确定 n。

所以可以考虑枚举 \operatorname{popcount},然后判断满不满足要求。

Code:

#include<bits/stdc++.h>
using namespace std;
#define int long long
signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0),cout.tie(0);
    int t;cin>>t;while(t--){
        int a;cin>>a;
        int flag=0;
        if((int)pow(2,(int)log2(a))==a){
            cout<<a<<"\n";continue;
        }
        for(int i=1;i<=100;i++){
            int n=a*i;
            int pc=__builtin_popcountll(n);
            if(n==pc*a){
                cout<<n<<"\n";
                flag=1;break;
            }
        }
        if(!flag){cout<<"-1\n";}
    }
}

注:用 \operatorname{popcountll} 而不是 \operatorname{popcount}