Solution
先打表找规律
| n | 偶 | 奇 |
|---|---|---|
| 1 | 0 | 2 |
| 2 | 1 | 2 |
| 3 | 0 | 4 |
| 4 | 3 | 2 |
| 5 | 2 | 4 |
| 6 | 3 | 4 |
| 7 | 0 | 8 |
| 8 | 7 | 2 |
正难则反,所以把奇数个数也写出来,观察到奇数的个数都是 的幂次,继续找规律。
规律
第 行奇数的个数是
Proof
考虑 Lucas 定理。
对第 行中第 个数 ,设:
其中 ,允许有前导零。
由 Lucas 定理得 ,故 为奇数当且仅当 恒成立。而 ,所以若 ,则 ,有一种可能;若 ,则 或 ,有两种可能。
由乘法原理,符合要求的个数为 。
于是答案为 。
计算
目标是计算 。
这里使用数位 DP 思想。设 的二进制位数为 ,初始化 表示 从高位到低位被固定的前缀中 的个数,从第 位枚举到第 位,若其中 ,有两种选择:
- 令 ,此时已经可以确定 ,剩下的 位数可以任取,对 的贡献为:
- 令 ,此时 ,然后考虑下一位。
若 ,则必有 , 不变,直接考虑下一位。
最后还需要 (此时有 )表示 时的贡献并去掉多算的 。
Code
#include <bits/stdc++.h>
using namespace std;
// 高精度
struct BigInt {
bitset<1000> digits; // 从低位到高位,稍微开大一点
BigInt() {}
BigInt(int x) {
digits.reset();
int i=0;
while (x) {
if (x&1) digits.set(i);
x>>=1;
i++;
}
}
BigInt(const string& s) {
*this=BigInt(0);
for (char ch:s)
*this=*this*10+BigInt(ch-'0');
}
int len() const {
for (int i=999;i>=0;i--)
if (digits[i]) return i+1;
return 0;
}
bool at(int i) const {return digits[i];}
bool is0() const {return len()==0;}
BigInt operator+(const BigInt& other) const {
BigInt res;
bool carry=0;
for (int i=0;i<1000;i++) {
int sum=digits[i]+other.digits[i]+carry;
res.digits[i] = sum & 1;
carry=sum>>1;
}
return res;
}
BigInt operator+=(const BigInt& other) {
return *this=*this+other;
}
BigInt operator-(const BigInt& other) const {
BigInt res;
bool borrow=0;
for (int i=0;i<1000;i++) {
int diff=digits[i]-other.digits[i]-borrow;
if (diff<0) {
diff+=2;
borrow=1;
} else {
borrow=0;
}
res.digits[i]=diff;
}
return res;
}
BigInt operator<<(int x) const {
BigInt res;
res.digits=digits<<x;
return res;
}
BigInt operator>>(int x) const {
BigInt res;
res.digits=digits>>x;
return res;
}
BigInt operator*(const BigInt& other) const {
BigInt res;
for (int i=0;i<1000;i++)
if (other.digits[i])
res=res+((*this)<<i);
return res;
}
BigInt div2() const {
return *this>>1;
}
pair<BigInt,int> divmod10() const { // 除以 10 的余数和商,输出要用
BigInt Q; // 商
vector<bool> qbits;
int r=0; //余数
int l=len();
for (int i=l-1;i>=0;i--) {
r=(r<<1)|digits[i];
qbits.push_back(r/10);
r%=10;
}
int idx=0;
for (auto it=qbits.rbegin();it!=qbits.rend();it++) {
if (*it) Q.digits.set(idx);
idx++;
}
return {Q,r};
}
string toString() const {
if (is0()) return "0";
BigInt tmp=*this;
string s;
while (!tmp.is0()) {
auto [q,r]=tmp.divmod10();
s.push_back('0'+r);
tmp=q;
}
reverse(s.begin(),s.end());
return s;
}
}n,pow2[180],pow3[180]; // 10^50 有 167 位
// 预处理
void init() {
pow2[0]=pow3[0]=BigInt(1);
for (int i=1;i<180;i++) {
pow2[i]=pow2[i-1]*BigInt(2);
pow3[i]=pow3[i-1]*BigInt(3);
}
}
int main() {
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
init();
string s;
while (cin>>s) {
n=BigInt(s);
BigInt S(0);
int l=n.len(),cnt=0;
for (int i=l-1;i>=0;i--) {
if (n.at(i)==0) continue;
S+=pow2[cnt]*pow3[i];
cnt++;
}
S+=pow2[cnt]-BigInt(1); // 补上 m=n,去掉 m=0
cout<<((n*(n+BigInt(3))).div2()-S).toString()<<'\n';
}
return 0;
}