Rust Fundamentals · 15 XP Pro
while loops
while checks a condition before every round and stops as soon as it is false.
If the condition is false the first time, the body never runs at all.
let mut countdown = 3;
while countdown > 0 {
println!("{countdown}");
countdown -= 1;
}
while is a good fit when the loop is driven by a changing value rather than by a
fixed number of rounds. Something inside the body must move the value toward making
the condition false, otherwise you have written an infinite loop.
A classic trick: n / 10 drops the last decimal digit of an integer, and n % 10
reads it.
let mut n = 472;
while n > 0 {
let digit = n % 10; // 2, then 7, then 4
n /= 10;
}
Your task
- Write
count_digits(n: u64) -> u32that returns how many decimal digitsnhas. Treat0as having one digit. - Write
collatz_steps(n: u64) -> u32. Starting fromn(at least 1), repeat: if the number is even, halve it; if odd, replace it with3 * n + 1. Return how many steps it takes to reach1. For example6 -> 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1is 8 steps.