【ZR #541. 【19普转提 4】简单函数】题解

题目链接

题目

定义\(f(n) = |n - \sum_{d|n,d\not =n}d|\)

每次给出\(A,B\),求\(\sum_{i=A}^B f(i)\)

对于\(100\%\)的数据,\(A,B\le 10^7\)

思路

看到 \(A,B\) 的范围,想着能不能快速求 \(f(n)\)

难点就在于求 \(\sum_{d|n,d\not =n}d\),就是求一个数除自己的因子的和。

可以用类似筛的思想,一个 \(O(n\log n)\) 解决。

总结

模拟赛时没打出这题,归根到底还是胆小了。

看到题目的数据范围,即使下面有个3秒,第一个反应还是 \(O(n)\),完全没打 \(O(n\log n)\),很崩溃。

最后就只能乱打了个 \(O(n\sqrt n)\) 交上去。

从中我也得到一个启示:有些时候 \(O(n\log n)\) 能过 \(1e7\) 的数据。

就像NOIP2021T1一样。

orz HJH \(O(n)\) 做法。

Code

#include<bits/stdc++.h>
using namespace std;
#define int long long
inline int read(){int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;
ch=getchar();}while(ch>='0'&&ch<='9'){x=(x<<1)+
(x<<3)+(ch^48);ch=getchar();}return x*f;}
#define N 10000010
//#define M
//#define mo
int n, m, i, j, k; 
int a, b, f[N]; 

signed main()
{
//	freopen("tiaoshi.in","r",stdin);
//	freopen("tiaoshi.out","w",stdout);
	a=read(); b=read(); 
	for(i=1; i<=b; ++i)
		for(j=i+i; j<=b; j+=i) f[j]+=i; 
	for(i=a; i<=b; ++i) m+=abs(i-f[i]); 
	printf("%lld", m); 
	return 0;
}

posted @ 2022-01-09 11:04  zhangtingxi  阅读(45)  评论(0编辑  收藏  举报