加速python3代码,一个codechef问题INSQ17R

时间:2017-09-11 17:12:33

标签: python algorithm python-3.x binary

我希望Python代码总结为第n个整数,并且每个整数乘以其二进制表示数字中的“1”数。这是我的python代码,但n> = 10 ** 8:

需要很长时间
from functools import reduce
from operator import add
m = 10**9+7
for t in range(int(input())):
    n = int(input())
    w =reduce(add,tuple(i*bin(i).count('1') for i in range(1,n+1)))
print((w)%m)

1 个答案:

答案 0 :(得分:0)

我在C ++中完成您可以检查您的参考:

const long long mod = 1e9 + 7;

int main()

{

int T;

cin>>吨;

for(int t = 0; t< T; t ++)

{

   int N, Nt;

   vector<int> Nb;

   long long mult = 1, sol = 0;

   cin >> N;

   N++;

   Nt = N;

   while (N > 0) {

       Nb.push_back(N % 2);

       N /= 2;

   }

   N = Nt;

   //reverse(Nb.begin(), Nb.end());

   vector<long long> g(Nb.size()), h(Nb.size()), cs(Nb.size());

   for (int i = 1; i < Nb.size(); i++) {

       g[i] = (g[i - 1] * 2 + mult) % mod;

       h[i] = (h[i - 1] * 2 + ((mult * (mult - 1)) / 2) + (g[i - 1] + mult) *

mult)%mod;

       mult = mult * 2;

   }

   mult = 1;

   for (int i = Nb.size() - 2; i >= 0; i--)


       cs[i] = cs[i + 1] + Nb[i + 1];

   for (int i = 0; i < Nb.size(); i++) {

       long long NN = N / (2 * mult);

       if (Nb[i]) {

           sol = (sol + 2 * NN * mult * (g[i] + cs[i] * mult) + h[i] + cs[i] *

((mult *(mult-1))/ 2))%mod;

       }

       mult = mult * 2;

   }

   cout << sol << endl;

}

返回0;

}  `