P1403
暴力枚举,代码就不贴了.
就是常用的枚举约数法,枚举到
int f(int x){
int ans = 0;
for (int i = 1;i * i <= x;i++)
if (x % i == 0){
ans++;
if (i != x / i) ans++;
}
return ans;
}
同复杂度,但可
其实约数个数还用一种表达方法就是把
int f(int x){
int ans = 1;
for (int i = 2;i * i <= x;i++){
int cnt = 0;
while (x % i == 0) x /= i,cnt++;
ans *= cnt + 1;
}
if (x != 1) ans *= 2;
return ans;
}
正解:
1:
求一串数通常可以用“筛法”,本题也是一样,枚举
for (int i = 1;i <= n;i++)
for (int j = i;j <= n;j += i)
f[j]++;
2:
本题只要求和,所以可以将前面的位置
for (int i = 1;i <= n;i++) ans += n / i;
3:
这个很容易想到除法分块,贴一下完整代码吧:
#include <iostream>
int main(){
std::cin.tie(0)->sync_with_stdio(0);
int n;
long ans = 0;
std::cin >> n;
for (int i = 1,j;i <= n;i = j + 1)
j = n / (n / i),ans += (n / i) * (j - i + 1);
std::cout << ans << '\n';
return 0;
}