1 条题解

  • 1
    @ 2024-10-24 11:53:44

    [CSP-J 2023] 一元二次方程 题解

    大模拟!

    解题思路

    题目比较长,但中心就是求一元二次方程的最大实数解,否则输出 NO,读题就可以知道:

    Δ = b2  4ac\Delta \ = \ b^{2} \ - \ 4ac

    如果 Δ < 0\Delta \ < \ 0,就没有实数解

    如果 Δ 0\Delta \ \ge 0,就依照题意来写:

    两个实数解 x1,2 = b±Δ2ax_{1,2} \ = \ \frac{-b\pm \sqrt{\Delta} }{2a}

    2a < 02a \ < \ 0 时,应当用 b±Δ2a\frac{-b\pm \sqrt{\Delta} }{2a}

    AC Code

    # include <bits/stdc++.h>
    using namespace std;
    bool kaifang(int x) {
    	int k = sqrt(x);
    	return k * k == x;
    }
    void huajie(int fenzi, int fenmu) {
    	int fu = 1;
    	if (fenzi  < 0) {
    		fu = -1;
    		fenzi = -fenzi;
    	}
    	int k = __gcd(fenzi, fenmu);
    	fenzi /= k;
    	fenmu /= k;
    	if (fenzi % fenmu == 0) {
    		cout << fu * fenzi / fenmu;
    	} else {
    		cout << fenzi * fu << "/" << fenmu;
    	}
    }
    int check(int x) {
    	int ret = 1;
    	for (int i = 2; i * i <= x; i++) {
    		if (x % (i * i) == 0) {
    			ret = i;
    		}
    	}
    	return ret;
    }
    void huajie2(int fenzi, int fenmu, int delta) {
    	if (fenzi % fenmu == 0) {
    		if (fenzi / fenmu == 1) {
    			cout << "sqrt(" << delta << ")" << "\n";
    		} else {
    			cout << fenzi / fenmu << "*sqrt(" << delta << ")" << "\n";
    		}
    		return;
    	}
    	int k = __gcd(fenzi, fenmu);
    	fenzi /= k;
    	fenmu /= k;
    	if (fenzi == 1) {
    		cout << "sqrt(" << delta << ")/" << fenmu << "\n";
    	} else {
    		cout << fenzi << "*sqrt(" << delta << ")/" << fenmu << "\n";
    	}
    }
    int main() {
        freopen("uqe.in", "r", stdin);
        freopen("uqe.out", "w", stdout);
    	int T, M;
    	scanf("%d%d", &T, &M);
    	while (T--) {
    		int a, b, c;
    		scanf("%d%d%d", &a, &b, &c);
    		if (a < 0) {
    			a *= -1;
    			b *= -1;
    			c *= -1;
    		}
    		int delta = b * b - 4 * a * c;
    		if (delta < 0) {
    			printf("NO\n");
    			continue;
    		}
    		if (kaifang(delta)) {
    			int ret;
    			int flag = 0;
    			int k = sqrt(delta);
    			ret = (-b + k) / (2 * a);
    			if ((-b + k) % (2 * a) == 0) {
    				printf("%d\n", ret);
    				continue;
    			}
    			huajie(-b + sqrt(delta), 2 * a);
    			printf("\n");
    			continue;
    		}
    		if (b != 0) {
    			huajie(-b, 2 * a);
    			printf("+");
    		}
    		int yinzi = check(delta);
    		delta /= yinzi * yinzi;
    		huajie2(yinzi, 2 * a, delta);
    	}
        return 0;
    }
    
    • 1

    信息

    ID
    308
    时间
    1000ms
    内存
    512MiB
    难度
    9
    标签
    递交数
    13
    已通过
    3
    上传者