Unit 5 · Lesson 130 minAcademic review pending

Turn mathematics into guarded steps

Design algorithms for quadratic roots, minima and maxima, and primality with explicit edge cases.

Choose explanation

After this lesson

You should be able to

  • Translate a mathematical formula into ordered checks and calculations.
  • Reduce primality tests to divisors no greater than the square root.
01

Guard the formula's domain

For ax² + bx + c = 0, first handle a = 0 because the equation is then not quadratic. Compute the discriminant d = b² − 4ac. Positive d gives two real roots, zero gives one repeated real root, and negative d has no real roots.

Algorithm design is more than copying the final formula. It orders validity checks before risky operations such as division and square root.

Real-root branch
double d = b * b - 4.0 * a * c;

if (a == 0.0) {
    printf("Not a quadratic equation\n");
} else if (d < 0.0) {
    printf("No real roots\n");
} else {
    double root = sqrt(d);
    double x1 = (-b + root) / (2.0 * a);
    double x2 = (-b - root) / (2.0 * a);
    printf("%.3f %.3f\n", x1, x2);
}
02

Primality needs only possible factors

A prime integer is greater than one and has no positive divisors other than one and itself. If n has a factor larger than its square root, the matching factor is smaller than the square root. Therefore testing all larger divisors is unnecessary.

After rejecting n < 2, test divisors from 2 while divisor <= n / divisor. Using division in the condition avoids possible overflow from divisor * divisor.

Primality test
bool is_prime(int n) {
    if (n < 2) return false;

    for (int divisor = 2; divisor <= n / divisor; divisor++) {
        if (n % divisor == 0) return false;
    }
    return true;
}

Try it yourself

List the divisors tested when checking whether 29 is prime.

Need a hint?

Stop after the largest integer not exceeding √29.

Check the worked solution

Test 2, 3, 4, and 5. None divides 29, so 29 is prime.

Quick check

Why can a primality test stop at √n?

Select an answer to check your thinking.

Why this lesson exists

Syllabus mapping

Quadratic roots · Minimum and maximum values · Primality

Maps to course outcomes CO1, CO2, CO3.