Rust Program: Find Prime numbers in Range
Rust Iterators and Iterator Adapters: Exercise-15 with Solution
Write a Rust program that iterates over a range of numbers and checks if each number is prime. Return a new vector containing only prime numbers.
Sample Solution:
Rust Code:
// Function to check if a number is prime
fn is_prime(n: u32) -> bool {
if n <= 1 {
return false;
}
// Check divisibility from 2 to square root of n
for i in 2..=(n as f64).sqrt() as u32 {
if n % i == 0 {
return false;
}
}
true // If not divisible by any number, it's prime
}
// Function to find prime numbers in a given range
fn primes_in_range(start: u32, end: u32) -> Vec<u32> {
// Use filter to collect prime numbers within the range
(start..=end)
.filter(|&x| is_prime(x))
.collect()
}
fn main() {
let start = 1; // Starting point of the range
let end = 30; // Ending point of the range
// Find prime numbers within the specified range
let prime_numbers = primes_in_range(start, end);
// Print the prime numbers found within the range
println!("Prime numbers in range {:?} to {:?}: \n{:?}", start, end, prime_numbers);
}
Output:
Prime numbers in range 1 to 30: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
Explanation:
In the exercise above,
- The "is_prime()" function checks whether a given number is prime. It returns 'true' if the number is prime and 'false' otherwise.
- The "primes_in_range()" function generates a vector containing prime numbers within a given range. It uses the "filter()" method along with the "is_prime()" function to filter out non-prime numbers from the range.
- In the "main()" function, we define the range of numbers (start to end) and call the "primes_in_range()" function to get the prime numbers within that range. Finally, we print the result.
Rust Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/rust/functional-programming/rust-iteretors-and-iterator-adapters-exercise-15.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics