题目描述
You are given a positive integer N.
Find the number of quadruples of positive integers (A,B,C,D) such that AB+CD=N. Under the constraints of this problem, it can be proved that the answer is at most
9
×
1
0
18
9×10^{18}
9×1018.
分析
要求AB+CD=N的组合数,如果暴力枚举将达到 N 3 N^3 N3的复杂度。
将问题分解,求出满足 A B = X , C D = Y , X + Y = N AB=X,CD=Y,X+Y=N AB=X,CD=Y,X+Y=N的个数。那么只要确定X,A,C即可,此时复杂度降为了 N 2 N^2 N2。继续简化:不妨设 A ≤ B A\le B A≤B,那么A只会取到 ≤ N \le \sqrt N ≤N的值,复杂度为 O ( n n ) O(n\sqrt n) O(nn)。
本题关键:将问题拆分为两个小的求和问题的叠加,可以使复杂度从乘积的数量级降到求和的数量级。另外,很多数学问题枚举因数时只需枚举到根号之下即可。
代码
#include<bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
int x, y;
long long ans = 0;
for (int i = 0; i <= n; ++i) {
x = i, y = n - i;
long long cnt1 = 0, cnt2 = 0;
for (int j = 1; j * j <= x; ++j) {
if (x % j == 0) {
++cnt1;
if (j * j != x)
++cnt1;
}
}
for (int j = 1; j * j <= y; ++j) {
if (y % j == 0) {
++cnt2;
if (j * j != y)
++cnt2;
}
}
ans += cnt1 * cnt2;
}
cout << ans;
return 0;
}