Yuki 550 夏休みの思い出(1)
Problem Description:
Solve f(x) = x * x * x + A * x * x + B * x + C, given A, B, and C. Output the solutions in increasing order.
Constraints:
-1e18 < A, B, C < 1e18
-1e9 < min(sol) < max(sol) < 1e9
It is guaranteed that there are exactly 3 distinct solutions
Solution:
pekempey showed this clever solution:
We want to make use of the knowledge that the solution is bounded by integer range.
Consider deciding a mod = sqrt(1e9).
We can first complete search on this modulo equivalence relation:
g(x) = f(x) % mod = 0
It takes only O(mod = sqrt(1e9)) to solve for solutions under mod equivalence.
We will have a constant number (at least 1, less than 3) solutions, suppose one of them is x, then we know that we should search for values that are of form x + mod * i, for i in -mod..mod. Again this takes only O(mod) time.
Code:
#include <bits/stdc++.h> template<typename T> std::ostream& operator<<(std::ostream &os, const std::vector<T> &vec) { for (size_t i = 0; i < vec.size(); ++i) { os << vec[i] << " \n"[i + 1 == vec.size()]; } return os; } std::vector<long long> solve_mod(long long a, long long b, long long c) { constexpr int maxs = 1e9; constexpr int mod = std::sqrt(maxs) + 10; std::vector<int> sol_mod; for (int i = 0; i < mod; ++i) { int aa = a % mod; int bb = b % mod; int cc = c % mod; int s = i * i % mod * i % mod; (s += aa * i % mod * i % mod) %= mod; (s += bb * i % mod) %= mod; (s += cc) %= mod; if (s == 0) sol_mod.emplace_back(i); } std::vector<long long> sol; for (int x : sol_mod) { for (int i = -mod; i < mod; ++i) { __int128 xx = x + static_cast<__int128>(i) * mod; __int128 s = xx * xx * xx + xx * xx * a + xx * b + c; if (s == 0) sol.emplace_back(xx); } } std::sort(sol.begin(), sol.end()); return sol; } signed main() { std::ios::sync_with_stdio(false); long long A, B, C; std::cin >> A >> B >> C; std::cout << solve_mod(A, B, C) << std::endl; return 0; }