洛谷T422586 factor

题意

∑ i = 1 n d ( i ) × i \sum_{i=1}^{n}d(i)\times i i=1nd(i)×i
其中的 d ( i ) d(i) d(i) 表示 i i i约数 个数,也就是因数个数

50分

暴力就行,但是可以优化,求因数的时候不用到 n n n,只用到 n / 2 n/2 n/2就行
注意取模,不然会爆long long
code↓

#include 
using namespace std;
const int mod=1e9+7;
const int maxn=1e6+2;
long long n,sum=0,a[maxn]={};
int main(){
//	freopen("factor.in","r",stdin);
//	freopen("factor.out","w",stdout);
	cin>>n;
	for(long long i=1;i<=n;i++){
		long long ans=1;
		for(long long j=1;j<=i/2;j++){
			if(i%j==0){
				ans++;
			}
		}
		sum=(sum+ans%mod*i%mod)%mod;
	}
	cout<<sum%mod;
	return 0;
}

100分做法

∑ i = 1 x d ( i ) × i \sum_{i=1}^{x}d(i)\times i i=1xd(i)×i

= ∑ i = 1 n ( ∑ i = 1 n [ j ÷ i ] ) × i =\sum_{i=1}^{n}(\sum_{i=1}^{n}[j{\div} i])\times i =i=1n(i=1n[j÷i])×i

= ∑ i = 1 n ∑ i = 1 n ( [ j ÷ i ] × i ) =\sum_{i=1}^{n}\sum_{i=1}^{n}([j{\div} i]\times i) =i=1ni=1n([j÷i]×i)

= ∑ j = 1 n j × ∑ i = 1 n ÷ j i =\sum_{j=1}^{n}j\times\sum_{i=1}^{n{\div}j}i =j=1nj×i=1n÷ji

= ∑ j = 1 n j × ( n ÷ j ) × ( n j + 1 ) 2 =\sum_{j=1}^{n}j\times \frac{(n{\div}j)\times (\frac{n}{j}+1)}{2} =j=1nj×2(n÷j)×(jn+1)

code↓

#include
#define ll long long
using namespace std;
ll n,mod=1000000007,ans,l=1,x,r,sum,cnt;
int main(){
//	freopen("factor.in","r",stdin);
//	freopen("factor.out","w",stdout);
	scanf("%lld",&n);
	while(1){
		l=r+1,x=n/l,r=n/x,sum=cnt=0;
		if(x%2==0){
            sum=((x/2)%mod)*((x+1)%mod)%mod;
        }
		else{
            sum=(x%mod)*(((x+1)/2)%mod)%mod;
        }
		if((l+r)%2==0){
            cnt=(((l+r)/2)%mod)*((r-l+1)%mod)%mod;
        }
		else{
            cnt=((l+r)%mod)*(((r-l+1)/2)%mod)%mod;
        }
		ans=(ans+(sum*cnt)%mod)%mod;
		if(r==n){
            break;
        }
	}
	printf("%lld",ans);
	return 0;
}//code:wjj2011

你可能感兴趣的:(luogu_topic,c语言,c++)