【题目来源】
https://www.luogu.com.cn/problem/P9750
https://www.acwing.com/problem/content/5312/
【算法分析】
○ 本题不涉及复杂的算法,充其量只是复杂一点儿的模拟题。故本题的代码相对简单,就是将给定的一元二次方程的较大解,按要求的格式输出而已。
○ 两个整数 a、b 的商 a/b,若表示为分数形式,则为 [a÷gcd(a,b)]/[b÷gcd(a,b)]。其中,gcd(a,b) 表示整数 a 与 b 的最大公约数。
○ 辗转相除法求最大公约数的代码详见:https://blog.csdn.net/hnjzsyjyj/article/details/110733164
【算法代码】
#include <bits/stdc++.h>
using namespace std;
int gcd(int a,int b) {
if(b==0) return a;
else return gcd(b,a%b);
}
int T,M;
int a,b,c,delta;
int k; //square root value in integer form
int t; //common factor
int main() {
cin>>T>>M;
for(int i=1; i<=T; i++) {
cin>>a>>b>>c;
if(a<0) a=-a,b=-b,c=-c;
delta=b*b-4*a*c;
if(delta<0) {
cout<<"NO"<<endl;
continue;
}
k=1;
for(int i=2; i*i<=delta; i++) { //Simply delta
while(delta%(i*i)==0) { //Get k and delta
k*=i;
delta/=(i*i);
}
}
if(delta==0 || delta==1) { //Can obtain square roots in integer form
t=abs(gcd(2*a,-b+k*delta));
cout<<(-b+k*delta)/t;
if(2*a/t != 1) cout<<"/"<<2*a/t;
cout<<endl;
continue;
}
t=abs(gcd(-b,2*a)); //common factor
if(-b/t==0) goto g; //Indicates that -b/2a is 0
cout<<-b/t;
if(2*a/t != 1) cout<<"/"<<2*a/t;
cout<<"+";
g:
t=abs(gcd(k,2*a));
if(k/t != 1) cout<<k/t<<"*"; //Can't obtain square roots in integer form
cout<<"sqrt("<<delta<<")";
if(2*a/t != 1) cout<<"/"<<2*a/t;
cout<<endl;
}
return 0;
}
/*
in:
9 1000
1 -1 0
-1 -1 -1
1 -2 1
1 5 4
4 4 1
1 0 -432
1 -3 1
2 -4 1
1 7 1
out:
1
NO
1
-1
-1/2
12*sqrt(3)
3/2+sqrt(5)/2
1+sqrt(2)/2
-7/2+3*sqrt(5)/2
*/
【参考文献】
https://blog.csdn.net/Dcsworld/article/details/134478817
https://blog.csdn.net/hnjzsyjyj/article/details/118818750
https://zhuanlan.zhihu.com/p/663318222
https://mp.weixin.qq.com/s/zckJsihxsDT2JNBFK1ipxA
https://www.luogu.com.cn/problem/solution/P9750
https://blog.csdn.net/wangchenyu22/article/details/134998431