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,12 +1,19 @@
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 {
0..=1 => 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 { if num % i == 0 {
return false; return false;
} }
} }
prime prime
} }
}
}
fn main() { fn main() {
let mut primes: Vec<u64> = vec![]; let mut primes: Vec<u64> = vec![];
@ -19,5 +26,5 @@ fn main() {
increment += 1; increment += 1;
} }
println!("{:?}", primes); println!("{:?}", primes[primes.len()-1]);
} }