Initial solution to nth prime

This commit is contained in:
Avery Winters 2024-11-06 12:39:39 -06:00
parent 551dff82a2
commit 0f87a7d30b
Signed by: avery
SSH key fingerprint: SHA256:eesvLB5MMqHLZrAMFt6kEhqJWnASMLcET6Sgmw0FqZI
8 changed files with 290 additions and 0 deletions

View file

@ -0,0 +1,37 @@
{
"authors": [
"sacherjj"
],
"contributors": [
"attilahorvath",
"cbzehner",
"coriolinus",
"cwhakes",
"eddyp",
"efx",
"ErikSchierboom",
"imbolc",
"lutostag",
"nfiles",
"petertseng",
"rofrol",
"stringparser",
"xakon",
"ZapAnton"
],
"files": {
"solution": [
"src/lib.rs",
"Cargo.toml"
],
"test": [
"tests/nth-prime.rs"
],
"example": [
".meta/example.rs"
]
},
"blurb": "Given a number n, determine what the nth prime is.",
"source": "A variation on Problem 7 at Project Euler",
"source_url": "https://projecteuler.net/problem=7"
}

View file

@ -0,0 +1 @@
{"track":"rust","exercise":"nth-prime","id":"ed13a93505c3473a9877a23fdf9e38b3","url":"https://exercism.org/tracks/rust/exercises/nth-prime","handle":"averywinters","is_requester":true,"auto_approve":false}

8
rust/nth-prime/.gitignore vendored Normal file
View file

@ -0,0 +1,8 @@
# Generated by Cargo
# will have compiled files and executables
/target/
**/*.rs.bk
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
# More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock
Cargo.lock

View file

@ -0,0 +1,4 @@
[package]
edition = "2021"
name = "nth_prime"
version = "2.1.0"

86
rust/nth-prime/HELP.md Normal file
View file

@ -0,0 +1,86 @@
# Help
## Running the tests
Execute the tests with:
```bash
$ cargo test
```
All but the first test have been ignored. After you get the first test to
pass, open the tests source file which is located in the `tests` directory
and remove the `#[ignore]` flag from the next test and get the tests to pass
again. Each separate test is a function with `#[test]` flag above it.
Continue, until you pass every test.
If you wish to run _only ignored_ tests without editing the tests source file, use:
```bash
$ cargo test -- --ignored
```
If you are using Rust 1.51 or later, you can run _all_ tests with
```bash
$ cargo test -- --include-ignored
```
To run a specific test, for example `some_test`, you can use:
```bash
$ cargo test some_test
```
If the specific test is ignored, use:
```bash
$ cargo test some_test -- --ignored
```
To learn more about Rust tests refer to the online [test documentation][rust-tests].
[rust-tests]: https://doc.rust-lang.org/book/ch11-02-running-tests.html
## Submitting your solution
You can submit your solution using the `exercism submit src/lib.rs Cargo.toml` command.
This command will upload your solution to the Exercism website and print the solution page's URL.
It's possible to submit an incomplete solution which allows you to:
- See how others have completed the exercise
- Request help from a mentor
## Need to get help?
If you'd like help solving the exercise, check the following pages:
- The [Rust track's documentation](https://exercism.org/docs/tracks/rust)
- The [Rust track's programming category on the forum](https://forum.exercism.org/c/programming/rust)
- [Exercism's programming category on the forum](https://forum.exercism.org/c/programming/5)
- The [Frequently Asked Questions](https://exercism.org/docs/using/faqs)
Should those resources not suffice, you could submit your (incomplete) solution to request mentoring.
## Rust Installation
Refer to the [exercism help page][help-page] for Rust installation and learning
resources.
## Submitting the solution
Generally you should submit all files in which you implemented your solution (`src/lib.rs` in most cases). If you are using any external crates, please consider submitting the `Cargo.toml` file. This will make the review process faster and clearer.
## Feedback, Issues, Pull Requests
The GitHub [track repository][github] is the home for all of the Rust exercises. If you have feedback about an exercise, or want to help implement new exercises, head over there and create an issue. Members of the rust track team are happy to help!
If you want to know more about Exercism, take a look at the [contribution guide].
## Submitting Incomplete Solutions
It's possible to submit an incomplete solution so you can see how others have completed the exercise.
[help-page]: https://exercism.org/tracks/rust/learning
[github]: https://github.com/exercism/rust
[contribution guide]: https://exercism.org/docs/community/contributors

42
rust/nth-prime/README.md Normal file
View file

@ -0,0 +1,42 @@
# Nth Prime
Welcome to Nth Prime on Exercism's Rust Track.
If you need help running the tests or submitting your code, check out `HELP.md`.
## Instructions
Given a number n, determine what the nth prime is.
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
If your language provides methods in the standard library to deal with prime numbers, pretend they don't exist and implement them yourself.
Remember that while people commonly count with 1-based indexing (i.e. "the 6th prime is 13"), many programming languages, including Rust, use 0-based indexing (i.e. `primes[5] == 13`). Use 0-based indexing for your implementation.
## Source
### Created by
- @sacherjj
### Contributed to by
- @attilahorvath
- @cbzehner
- @coriolinus
- @cwhakes
- @eddyp
- @efx
- @ErikSchierboom
- @imbolc
- @lutostag
- @nfiles
- @petertseng
- @rofrol
- @stringparser
- @xakon
- @ZapAnton
### Based on
A variation on Problem 7 at Project Euler - https://projecteuler.net/problem=7

83
rust/nth-prime/src/lib.rs Normal file
View file

@ -0,0 +1,83 @@
pub fn nth(mut n: u32) -> u32 {
let upper_bound = upper_bound_nth_prime(n);
let upper_bound: usize = upper_bound as usize + 1;
let len = upper_bound.div_ceil(8);
let mut bytes = vec![u8::MAX; len];
let mask = (1 << 0) | (1 << 1);
bytes[0] &= !mask;
let bound: f64 = upper_bound as f64;
let bound = bound.sqrt();
let bound: usize = bound as usize;
for i in 2..=bound {
let mask = 1 << (i % 8);
let byte = bytes[i / 8];
if byte & mask != 0u8 {
let start = i * i;
for j in (start..=upper_bound).step_by(i.try_into().unwrap()) {
let mask = 1 << (j % 8);
bytes[j / 8] &= !mask;
}
}
}
for (i, byte) in bytes.iter().enumerate() {
let count = byte.count_ones();
if count >= n {
for j in 0..8 {
let mask = 1 << j;
if byte & mask != 0u8 {
if n == 0 {
return (8 * i + j) as u32;
}
n -= 1;
}
}
} else {
n -= count;
}
}
unreachable!()
}
fn upper_bound_nth_prime(n: u32) -> u32 {
// For small prime counts, the upper bound estimate is not big enough.
// Hardcode it to the 6th prime (13).
if n < 6 {
return 13;
}
let mut low = n;
let mut high = u32::MAX - 1;
while low < high {
let mid = low + (high - low) / 2;
let guess = {
let mid: f64 = mid.into();
mid / mid.ln()
};
if guess > n.into() {
high = mid - 1;
} else {
low = mid + 1;
}
}
high + 1
}
#[cfg(test)]
mod test {
use crate::upper_bound_nth_prime;
#[test]
fn greater_first_20() {
let primes = [
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
];
for (i, &p) in primes.iter().enumerate() {
let i = i.try_into().unwrap();
let upper_bound = upper_bound_nth_prime(i);
assert!(upper_bound >= p, "{upper_bound} < {p}");
}
}
}

View file

@ -0,0 +1,29 @@
use nth_prime::*;
#[test]
fn first_prime() {
let output = nth(0);
let expected = 2;
assert_eq!(output, expected);
}
#[test]
fn second_prime() {
let output = nth(1);
let expected = 3;
assert_eq!(output, expected);
}
#[test]
fn sixth_prime() {
let output = nth(5);
let expected = 13;
assert_eq!(output, expected);
}
#[test]
fn big_prime() {
let output = nth(10_000);
let expected = 104_743;
assert_eq!(output, expected);
}