跳到正文

题解

题解:AT_abc397_d [ABC397D] Cubes

wrh316约 2 分钟
原文
文章信息与版本

文章信息

发布
2025年3月16日
收录
2025年12月12日
更新
2026年11月14日
篇幅
约 2 分钟
获赞
1

版本

  1. v1当前

思路

首先,利用立方差公式 x3−y3=(x−y)(x2+xy+y2)x^3 - y^3 = (x - y)(x^2 + xy + y^2),将问题转化为寻找两个因数的组合。

然后,枚举可能的差值 i=x−yi = x - y,并检查 ii 是否为 nn 的因数。

最后,对于每个合法的 ii,构造二次方程并求解 yy,验证是否存在正整数解。

因为 ii 的范围最高可达到 4n3\sqrt[3]{4n},所以,枚举 ii 时到 4n+24n + 2 即可。

代码

C++
#include <bits/stdc++.h>
using namespace std;

typedef unsigned long long ull;
bool check(ull n) {
    ull s = sqrt(n);
    return (s * s == n);
}
void calc(ull n) {
    ull maxn = cbrt(4 * n) + 2;
    for (ull i = 1; i <= maxn; i++) {
        if (n % i != 0) continue;
        ull k = n / i;
        ull tmp = 12 * k - 3 * i * i;
        if (tmp < 0) continue;
        if (!check(tmp)) continue;
        ull s = sqrt(tmp);
        if ((s - 3 * i) % 6 != 0) continue;
        ull y = (s - 3 * i) / 6;
        if (y <= 0) continue;
        if (3 * y * y + 3 * y * i + i * i != k) continue;
        cout << (y + i) << " " << y;
        return ;
    }
    cout << "-1";
    return ;
}
int main() {
    ull n;
    cin >> n;
    calc(n);
    return 0;
}
原文
存档评论1 条抓取于