performance: iterate only through odd numbers in is_prime function

This commit is contained in:
Muhammad Nauman Raza 2024-11-20 12:28:50 +00:00
parent 49a87c045c
commit 8448a97a58
Signed by: devraza
GPG key ID: 91EAD6081011574B

View file

@ -1,11 +1,18 @@
fn is_prime(num: u64) -> bool { fn is_prime(num: u64) -> bool {
let prime: bool = true; let prime: bool = true;
for i in 2..=((num as f64).sqrt() as u64) { match num {
if num % i == 0 { 0..=1 => false,
return false; 2 => true,
num if num % 2 == 0 => false,
_ => {
for i in (3..=((num as f64).sqrt() as u64)).step_by(2) {
if num % i == 0 {
return false;
}
}
prime
} }
} }
prime
} }
fn main() { fn main() {
@ -19,5 +26,5 @@ fn main() {
increment += 1; increment += 1;
} }
println!("{:?}", primes); println!("{:?}", primes[primes.len()-1]);
} }