日期:2025年6月21日
ZeroJudge 題目連結:a006. 一元二次方程式
解題想法
先找判別式 $D = b^2 - 4ac$,如果 $D > 0$ 有相異實根,如果 $D = 0$ 為重根,如果 $D < 0$ 沒有實根。如果在 Python 可以用 math.sqrt 或是 0.5 次方開根號,如果在 C++ 可以用 cmath 函式庫的 sqrt 開根號。
Python 程式碼
使用時間約為 18 ms,記憶體約為 3.3 MB,通過測試。
import math
a, b, c = map(int, input().split())
D = b**2 - 4*a*c
if D > 0:
x1 = int((-b + math.sqrt(D))/(2*a))
x2 = int((-b - math.sqrt(D))/(2*a))
print(f"Two different roots x1={x1:d} , x2={x2:d}")
elif D == 0:
x = int(-b/(2*a))
print(f"Two same roots x={x:d}")
else:
print("No real root")
使用時間約為 18 ms,記憶體約為 3.3 MB,通過測試。
a, b, c = map(int, input().split())
D = b**2 - 4*a*c
if D > 0:
x1 = int((-b + D**0.5)/(2*a))
x2 = int((-b - D**0.5)/(2*a))
print(f"Two different roots x1={x1:d} , x2={x2:d}")
elif D == 0:
x = int(-b/(2*a))
print(f"Two same roots x={x:d}")
else:
print("No real root")
C++ 程式碼
使用時間約為 2 ms,記憶體約為 136 kB,通過測試。
#include <cstdio>
#include <cmath>
using namespace std;
int main() {
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
int D = b*b - 4*a*c;
if (D > 0) {
int x1 = int((-b + sqrt(D))/(2*a)), x2 = int((-b - sqrt(D))/(2*a));
printf("Two different roots x1=%d , x2=%d\n", x1, x2);
} else if (D == 0) {
int x = -b/(2*a);
printf("Two same roots x=%d\n", x);
} else {
puts("No real root");
}
return 0;
}
沒有留言:
張貼留言