Prime Number Check
🎯 In Python, you might write a prime check like this:
def is_perfect_square(n):
if n < 0:
return False
root = int(n**0.5)
return root * root == n
Checking primality in Rust follows similar logic to what you'd write in Python, but introduces a few language features worth understanding.
Early return
So far you've seen Rust functions where the last expression is the return value. But sometimes you want to bail out early — that's what return is for:
fn check(n: u64) -> bool {
if n == 0 {
return false; // exit immediately
}
// ... more logic ...
true // last expression = default return
}
Both styles are idiomatic. Use expression-based returns when the function flows naturally to a single result. Use return when you need to short-circuit — like rejecting invalid input before the main logic runs.
Type casting with as
To compute a square root, you need a float — but the input is u64. Rust won't convert automatically, so you cast with as:
let bytes: u64 = 1_500_000;
let megabytes = bytes as f64 / 1_000_000.0; // 1.5
let rounded = megabytes as u64; // 1
as is Rust's low-level cast. It works between numeric types, but be aware: casting a large u64 to f64 can lose precision (floats only have 53 bits of mantissa). For this exercise that's fine, but in general, prefer .try_into() when precision matters.
.step_by() — range with a step
Python's range() takes a step argument: range(3, 100, 2). In Rust, you chain .step_by() onto a range:
for i in (3..100).step_by(2) {
println!("{i}"); // 3, 5, 7, 9, ...
}
This is useful for skipping even numbers when checking divisors.
Login to see the full task and start coding.
Topics
This is a premium exercise
Log in to unlock the full exercise and start coding.
Login to access this exercise