You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
2.1 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include <bits/stdc++.h>
using namespace std;
int main() {
int T, m;
cin >> T >> m; // 方程数和系数的绝对值上限,这个m后面没有用到
while (T--) {
int a, b, c;
cin >> a >> b >> c; // 方程的a,b,c
int delta = b * b - 4 * a * c;
// 上来先判断
if (delta < 0) {
cout << "NO" << endl;
continue;
}
a = 2 * a;
b = -b;
if (a < 0) { // 当a<0时对a和b进行处理让a<0和a>0都是统一解,使得x1=(-b+sqrt(b^2-4ac))/2a是最大值
a = -a;
b = -b;
}
int q = 1, r = delta; // q:根号系数,r:通过初始值delta不断开根号剩余到根号里面的数值
for (int i = 2; i * i <= r; i++) {
while (r % (i * i) == 0) { // 如果i*i是r的因子,i可以开方出去
q = q * i; // 记录根号外的系数
r = r / (i * i); // r在变小
}
}
if (r == 1) { // 完全平方数
delta = 0;
b += q;
}
int gcd1 = __gcd(abs(b), a); // 分裂式第一项的最大公约数
int gcd2 = __gcd(q, a); // 分裂式第二项的最大公约数
if (delta == 0) {
if (b % a == 0)
cout << b / a;
else
cout << b / gcd1 << "/" << a / gcd1; // 分裂式第一项约分
} else { // delta>0的场景
if (b != 0) { // 前半部分的输出如果b==0则没有输出
if (b % a == 0)
cout << b / a;
else
cout << b / gcd1 << "/" << a / gcd1;
cout << "+";
}
if (q / gcd2 != 1) cout << q / gcd2 << "*";
cout << "sqrt(" << r << ")";
if (a / gcd2 != 1) cout << "/" << a / gcd2; // 处理分母的技巧,==1就不输出
}
cout << endl; // 最后统一换行
}
return 0;
}