CSP-J 2023 复赛第3题:一元二次方程

【题目来源】
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








 

  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值