From e379adfc21bb90773656a7995f813fc133ee47c0 Mon Sep 17 00:00:00 2001 From: Avery Winters Date: Wed, 6 Nov 2024 14:38:12 -0600 Subject: [PATCH] Solve prime factors --- rust/prime-factors/.exercism/config.json | 36 +++++++ rust/prime-factors/.exercism/metadata.json | 1 + rust/prime-factors/.gitignore | 8 ++ rust/prime-factors/Cargo.toml | 7 ++ rust/prime-factors/HELP.md | 86 +++++++++++++++ rust/prime-factors/README.md | 68 ++++++++++++ rust/prime-factors/src/lib.rs | 67 ++++++++++++ rust/prime-factors/tests/prime-factors.rs | 117 +++++++++++++++++++++ 8 files changed, 390 insertions(+) create mode 100644 rust/prime-factors/.exercism/config.json create mode 100644 rust/prime-factors/.exercism/metadata.json create mode 100644 rust/prime-factors/.gitignore create mode 100644 rust/prime-factors/Cargo.toml create mode 100644 rust/prime-factors/HELP.md create mode 100644 rust/prime-factors/README.md create mode 100644 rust/prime-factors/src/lib.rs create mode 100644 rust/prime-factors/tests/prime-factors.rs diff --git a/rust/prime-factors/.exercism/config.json b/rust/prime-factors/.exercism/config.json new file mode 100644 index 0000000..1d2e5d6 --- /dev/null +++ b/rust/prime-factors/.exercism/config.json @@ -0,0 +1,36 @@ +{ + "authors": [ + "sacherjj" + ], + "contributors": [ + "attilahorvath", + "coriolinus", + "cwhakes", + "eddyp", + "efx", + "ErikSchierboom", + "lutostag", + "nathanielknight", + "nfiles", + "petertseng", + "rofrol", + "stringparser", + "xakon", + "ZapAnton" + ], + "files": { + "solution": [ + "src/lib.rs", + "Cargo.toml" + ], + "test": [ + "tests/prime-factors.rs" + ], + "example": [ + ".meta/example.rs" + ] + }, + "blurb": "Compute the prime factors of a given natural number.", + "source": "The Prime Factors Kata by Uncle Bob", + "source_url": "https://web.archive.org/web/20221026171801/http://butunclebob.com/ArticleS.UncleBob.ThePrimeFactorsKata" +} diff --git a/rust/prime-factors/.exercism/metadata.json b/rust/prime-factors/.exercism/metadata.json new file mode 100644 index 0000000..90c34d6 --- /dev/null +++ b/rust/prime-factors/.exercism/metadata.json @@ -0,0 +1 @@ +{"track":"rust","exercise":"prime-factors","id":"4549f19ef1ab4733862bf88519ee9586","url":"https://exercism.org/tracks/rust/exercises/prime-factors","handle":"averywinters","is_requester":true,"auto_approve":false} \ No newline at end of file diff --git a/rust/prime-factors/.gitignore b/rust/prime-factors/.gitignore new file mode 100644 index 0000000..db7f315 --- /dev/null +++ b/rust/prime-factors/.gitignore @@ -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 diff --git a/rust/prime-factors/Cargo.toml b/rust/prime-factors/Cargo.toml new file mode 100644 index 0000000..d624041 --- /dev/null +++ b/rust/prime-factors/Cargo.toml @@ -0,0 +1,7 @@ +[package] +edition = "2021" +name = "prime_factors" +version = "1.1.0" + +[dependencies] +bit-set = "0.8.0" diff --git a/rust/prime-factors/HELP.md b/rust/prime-factors/HELP.md new file mode 100644 index 0000000..67add76 --- /dev/null +++ b/rust/prime-factors/HELP.md @@ -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 \ No newline at end of file diff --git a/rust/prime-factors/README.md b/rust/prime-factors/README.md new file mode 100644 index 0000000..1d530ed --- /dev/null +++ b/rust/prime-factors/README.md @@ -0,0 +1,68 @@ +# Prime Factors + +Welcome to Prime Factors on Exercism's Rust Track. +If you need help running the tests or submitting your code, check out `HELP.md`. + +## Instructions + +Compute the prime factors of a given natural number. + +A prime number is only evenly divisible by itself and 1. + +Note that 1 is not a prime number. + +## Example + +What are the prime factors of 60? + +- Our first divisor is 2. + 2 goes into 60, leaving 30. +- 2 goes into 30, leaving 15. + - 2 doesn't go cleanly into 15. + So let's move on to our next divisor, 3. +- 3 goes cleanly into 15, leaving 5. + - 3 does not go cleanly into 5. + The next possible factor is 4. + - 4 does not go cleanly into 5. + The next possible factor is 5. +- 5 does go cleanly into 5. +- We're left only with 1, so now, we're done. + +Our successful divisors in that computation represent the list of prime factors of 60: 2, 2, 3, and 5. + +You can check this yourself: + +```text +2 * 2 * 3 * 5 += 4 * 15 += 60 +``` + +Success! + +## Source + +### Created by + +- @sacherjj + +### Contributed to by + +- @attilahorvath +- @coriolinus +- @cwhakes +- @eddyp +- @efx +- @ErikSchierboom +- @lutostag +- @nathanielknight +- @nfiles +- @petertseng +- @rofrol +- @stringparser +- @xakon +- @ZapAnton + +### Based on + +The Prime Factors Kata by Uncle Bob - https://web.archive.org/web/20221026171801/http://butunclebob.com/ArticleS.UncleBob.ThePrimeFactorsKata \ No newline at end of file diff --git a/rust/prime-factors/src/lib.rs b/rust/prime-factors/src/lib.rs new file mode 100644 index 0000000..06353c8 --- /dev/null +++ b/rust/prime-factors/src/lib.rs @@ -0,0 +1,67 @@ +use ::bit_set::BitSet; + +pub fn factors(n: u64) -> Vec { + let n = n + .try_into() + .expect("usize is not large enough to factor a u64"); + let bound = isqrt(n); + + let mut not_primes = { + // We need to be able to store any integer up to and including the bound. + let capacity = bound + 1; + BitSet::with_capacity(capacity) + }; + + let mut factors = { + // Worst case number of factors is a power of 2, number of + // factors will be the number of bits needed to represent + // the number. + let capacity = ilog2(n); + Vec::with_capacity(capacity) + }; + + let mut reduced = n; + 'outer: for i in 2..=bound { + if not_primes.contains(i) { + continue; + } + while reduced % i == 0 { + { + let i = i + .try_into() + .expect("round-trip conversion from u64 to usize loses precision"); + // Ensure we allocated enough capacity for all factors. + assert!(factors.len() < factors.capacity()); + factors.push(i); + } + reduced /= i; + if reduced == 0 { + break 'outer; + } + } + for j in (i * i..=bound).step_by(i) { + // Ensure we allocated enough capacity for all non-primes. + assert!(j < not_primes.capacity()); + not_primes.insert(j); + } + } + + if reduced > 1 { + let reduced = reduced + .try_into() + .expect("round-trip conversion from u64 to usize loses precision"); + // Ensure we allocated enough capacity for all factors. + assert!(factors.len() < factors.capacity()); + factors.push(reduced); + } + + factors +} + +fn ilog2(n: usize) -> usize { + (n.checked_ilog2().unwrap_or(0)) as _ +} + +fn isqrt(n: usize) -> usize { + (n as f64).sqrt() as _ +} diff --git a/rust/prime-factors/tests/prime-factors.rs b/rust/prime-factors/tests/prime-factors.rs new file mode 100644 index 0000000..86f8605 --- /dev/null +++ b/rust/prime-factors/tests/prime-factors.rs @@ -0,0 +1,117 @@ +use prime_factors::*; + +#[test] +fn zero() { + let factors = factors(0); + let expected = []; + assert_eq!(factors, expected); +} + +#[test] +fn no_factors() { + let factors = factors(1); + let expected = []; + assert_eq!(factors, expected); +} + +#[test] +fn prime_number() { + let factors = factors(2); + let expected = [2]; + assert_eq!(factors, expected); +} + +#[test] +fn another_prime_number() { + let factors = factors(3); + let expected = [3]; + assert_eq!(factors, expected); +} + +#[test] +fn square_of_a_prime() { + let factors = factors(9); + let expected = [3, 3]; + assert_eq!(factors, expected); +} + +#[test] +fn product_of_first_prime() { + let factors = factors(4); + let expected = [2, 2]; + assert_eq!(factors, expected); +} + +#[test] +fn cube_of_a_prime() { + let factors = factors(8); + let expected = [2, 2, 2]; + assert_eq!(factors, expected); +} + +#[test] +fn product_of_second_prime() { + let factors = factors(27); + let expected = [3, 3, 3]; + assert_eq!(factors, expected); +} + +#[test] +fn product_of_third_prime() { + let factors = factors(625); + let expected = [5, 5, 5, 5]; + assert_eq!(factors, expected); +} + +#[test] +fn product_of_first_and_second_prime() { + let factors = factors(6); + let expected = [2, 3]; + assert_eq!(factors, expected); +} + +#[test] +fn product_of_primes_and_non_primes() { + let factors = factors(12); + let expected = [2, 2, 3]; + assert_eq!(factors, expected); +} + +#[test] +fn product_of_primes() { + let factors = factors(901_255); + let expected = [5, 17, 23, 461]; + assert_eq!(factors, expected); +} + +#[test] +fn factors_include_a_large_prime() { + let factors = factors(93_819_012_551); + let expected = [11, 9_539, 894_119]; + assert_eq!(factors, expected); +} + +#[test] +fn large_pow2() { + let factors = factors(1 << 32); + let expected = [2; 32]; + assert_eq!(factors, expected); +} + +#[test] +fn fuzz() { + for i in 1..(1 << 16) { + let factors = factors(i); + assert!(factors.iter().all(|x| is_prime(*x)), "{factors:?} of {i} are not all prime"); + let product: u64 = factors.iter().product(); + assert_eq!(product, i); + } +} + +fn is_prime(n: u64) -> bool { + (2..=isqrt(n)).all(|x| n % x != 0) +} + +fn isqrt(n: u64) -> u64 { + (n as f64).sqrt() as _ +}