【问题标题】:Speed Up python3 code, a codechef problem INSQ17R加速python3代码,一个codechef问题INSQ17R
【发布时间】:2018-02-20 00:13:35
【问题描述】:
我希望 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)
【问题讨论】:
标签:
python
algorithm
python-3.x
binary
【解决方案1】:
我已经在 C++ 中完成了您可以查看您的参考:
const long long mod = 1e9 + 7;
int main()
{
int T;
cin >> T;
for (int t = 0; 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;
}
`