Hi everyone,
I’d like to propose adding a specific, ignored test case to the Difference of Squares exercise to help students explore the concept of intermediate overflow.
The Problem
Many students implement sum_of_squares using the closed-form formula:
n * (n + 1) * (2n + 1) / 6
While this is mathematically optimal O(1), a standard u32 implementation in Rust will fail for n = 1290 due to intermediate overflow:
- The final result for n = 1290 is
716,395,265(fits easily inu32). - The intermediate product
n(n+1)(2n+1)is4,298,595,390. - The limit for
u32::MAXis4,294,967,295.
Even though the final answer fits in the return type, the calculation crashes in debug or wraps in release before the division by 6 occurs.
Proposed Test Case
I suggest adding this as a “bonus” test that is ignored by default. This ensures it doesn’t block the student from passing the exercise on the solution runner but serves as a great teaching moment for local development and mentorship.
#[test]
#[ignore]
/// This test checks for intermediate overflow.
/// Even if the final result fits in a u32, the product of n * (n+1) * (2n+1)
/// might exceed u32::MAX during calculation.
fn sum_of_squares_1290() {
assert_eq!(716_395_265, squares::sum_of_squares(1290));
}
Why add this?
- Learning Opportunity: It encourages students to think about type promotion (
as u64) or checked/saturating arithmetic. - Mentorship: It provides a concrete entry point for mentors to discuss how Rust handles integer overflow in different build profiles.
- Real-world Robustness: It highlights that “mathematically correct” code can still be “computationally fragile.”
I’m happy to prepare a PR if the maintainers agree this adds value to the track’s pedagogical goals!
Best regards,
Jegors