是时候来篇 O(log2n) 的题解啦。
solution
对于 1+2+3⋯+(n−1)+n 这样的数列,我们可以将其分成奇数和偶数两部分,奇数部分项数显然是 ⌈2n⌉,因为连续 n 个奇数相加之和等于项数的平方,所以数列中奇数相加的和为 ⌈2n⌉2。至于偶数,很显然一共有 ⌊2n⌋ 项,将每项除以 2,可得:1+2⋯+(⌊2n⌋−1)+⌊2n⌋
。设 f(x) 表示 1+2+3⋯+(x−1)+x 的和,则可得:
f(0)=0
f(1)=1
f(x)=2f(⌊2x⌋)+⌈2x⌉2(x≥2)
code
C++#include<iostream>
using namespace std;
int f(int x){
if(x==0){
return 0;
}
if(x==1){
return 1;
}
return 2*f(x/2)+((x+1)/2)*((x+1)/2);
}
int main(){
int n;
cin>>n;
cout<<f(n)<<endl;
return 0;
}