diff --git a/solutions/rust/nth-prime/1/Cargo.toml b/solutions/rust/nth-prime/1/Cargo.toml new file mode 100644 index 00000000..ce719bcd --- /dev/null +++ b/solutions/rust/nth-prime/1/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "nth_prime" +version = "0.1.0" +edition = "2024" + +# Not all libraries from crates.io are available in Exercism's test runner. +# The full list of available libraries is here: +# https://github.com/exercism/rust-test-runner/blob/main/local-registry/Cargo.toml +[dependencies] diff --git a/solutions/rust/nth-prime/1/src/lib.rs b/solutions/rust/nth-prime/1/src/lib.rs new file mode 100644 index 00000000..9384d343 --- /dev/null +++ b/solutions/rust/nth-prime/1/src/lib.rs @@ -0,0 +1,27 @@ +pub fn nth(n: u32) -> u32 { + let mut primes= Vec::new(); + let mut canditate = 2; + + while primes.len() <= n as usize { + let mut is_prime = true; + let sqrt_canditate = (canditate as f64).sqrt() as u32; + for &prime in primes.iter() { + if prime > sqrt_canditate { + break; + } + if canditate % prime == 0 { + is_prime = false; + break; + } + } + if is_prime { + primes.push(canditate); + } + if canditate == 2 { + canditate = 3; + } else { + canditate += 2; + } + } + primes[n as usize] +}