第一题:一元二次方程的求解
问题描述
给定一元二次方程 ( ax^2 + bx + c = 0 ),其中 ( a \neq 0 ),求解方程的根。
解题步骤
- 计算判别式:判别式 ( \Delta = b^2 - 4ac )。
- 判断根的情况:
- 如果 ( \Delta > 0 ),方程有两个不相等的实数根。
- 如果 ( \Delta = 0 ),方程有两个相等的实数根。
- 如果 ( \Delta < 0 ),方程没有实数根。
- 求解根:
- 当 ( \Delta \geq 0 ) 时,使用公式 ( x = \frac{-b \pm \sqrt{\Delta}}{2a} ) 求解根。
代码示例
import math
def solve_quadratic_equation(a, b, c):
delta = b**2 - 4*a*c
if delta > 0:
x1 = (-b + math.sqrt(delta)) / (2*a)
x2 = (-b - math.sqrt(delta)) / (2*a)
return x1, x2
elif delta == 0:
x = -b / (2*a)
return x, x
else:
return None, None
# 示例
a, b, c = 1, -5, 6
roots = solve_quadratic_equation(a, b, c)
print(f"The roots of the equation {a}x^2 + {b}x + {c} = 0 are: {roots}")
第二题:数列求和
问题描述
给定一个数列 ( a_1, a_2, a_3, \ldots, a_n ),求该数列的前 ( n ) 项和 ( S_n )。
解题步骤
- 初始化和:将和 ( S ) 初始化为 0。
- 遍历数列:遍历数列中的每个元素,将其累加到和 ( S ) 中。
- 返回结果:返回累加后的和 ( S )。
代码示例
def sum_of_series(a, n):
total_sum = 0
for i in range(n):
total_sum += a[i]
return total_sum
# 示例
sequence = [1, 2, 3, 4, 5]
n = len(sequence)
sum_result = sum_of_series(sequence, n)
print(f"The sum of the first {n} terms of the sequence is: {sum_result}")
第三题:最大公约数
问题描述
给定两个正整数 ( m ) 和 ( n ),求它们的最大公约数(GCD)。
解题步骤
- 使用辗转相除法:重复以下步骤,直到 ( n ) 为 0:
- 计算 ( m ) 除以 ( n ) 的余数 ( r )。
- 将 ( m ) 设置为 ( n ),将 ( n ) 设置为 ( r )。
- 返回结果:当 ( n ) 为 0 时,( m ) 即为最大公约数。
代码示例
def gcd(m, n):
while n != 0:
r = m % n
m, n = n, r
return m
# 示例
m, n = 60, 48
gcd_result = gcd(m, n)
print(f"The GCD of {m} and {n} is: {gcd_result}")
