Avatar of izderadicka

izderadicka's solution

to Pythagorean Triplet in the Rust Track

Published at Sep 27 2019 · 0 comments
Instructions
Test suite
Solution

A Pythagorean triplet is a set of three natural numbers, {a, b, c}, for which,

a**2 + b**2 = c**2

and such that,

a < b < c

For example,

3**2 + 4**2 = 9 + 16 = 25 = 5**2.

Given an input integer N, find all Pythagorean triplets for which a + b + c = N.

For example, with N = 1000, there is exactly one Pythagorean triplet for which a + b + c = 1000: {200, 375, 425}.

Rust Installation

Refer to the exercism help page for Rust installation and learning resources.

Writing the Code

Execute the tests with:

$ 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 all ignored tests without editing the tests source file, use:

$ cargo test -- --ignored

To run a specific test, for example some_test, you can use:

$ cargo test some_test

If the specific test is ignored use:

$ cargo test some_test -- --ignored

To learn more about Rust tests refer to the online test documentation

Make sure to read the Modules chapter if you haven't already, it will help you with organizing your files.

Further improvements

After you have solved the exercise, please consider using the additional utilities, described in the installation guide, to further refine your final solution.

To format your solution, inside the solution directory use

cargo fmt

To see, if your solution contains some common ineffective use cases, inside the solution directory use

cargo clippy --all-targets

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 exercism/rust repository on 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.

Source

Problem 9 at Project Euler http://projecteuler.net/problem=9

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

pythagorean-triplet.rs

use pythagorean_triplet::find;
use std::{collections::HashSet, iter::FromIterator};

fn process_tripletswithsum_case(sum: u32, expected: &[[u32; 3]]) {
    let triplets = find(sum);

    if !expected.is_empty() {
        let expected = HashSet::from_iter(expected.iter().cloned());

        assert_eq!(expected, triplets);
    } else {
        assert!(triplets.is_empty());
    }
}

#[test]
fn test_triplets_whose_sum_is_12() {
    process_tripletswithsum_case(12, &[[3, 4, 5]]);
}

#[test]
#[ignore]
fn test_triplets_whose_sum_is_108() {
    process_tripletswithsum_case(108, &[[27, 36, 45]]);
}

#[test]
#[ignore]
fn test_triplets_whose_sum_is_1000() {
    process_tripletswithsum_case(1000, &[[200, 375, 425]]);
}

#[test]
#[ignore]
fn test_no_matching_triplets_for_1001() {
    process_tripletswithsum_case(1001, &[]);
}

#[test]
#[ignore]
fn test_returns_all_matching_triplets() {
    process_tripletswithsum_case(90, &[[9, 40, 41], [15, 36, 39]]);
}

#[test]
#[ignore]
fn test_several_matching_triplets() {
    process_tripletswithsum_case(
        840,
        &[
            [40, 399, 401],
            [56, 390, 394],
            [105, 360, 375],
            [120, 350, 370],
            [140, 336, 364],
            [168, 315, 357],
            [210, 280, 350],
            [240, 252, 348],
        ],
    );
}

#[test]
#[ignore]
fn test_triplets_for_large_number() {
    process_tripletswithsum_case(
        30_000,
        &[
            [1200, 14_375, 14_425],
            [1875, 14_000, 14_125],
            [5000, 12_000, 13_000],
            [6000, 11_250, 12_750],
            [7500, 10_000, 12_500],
        ],
    );
}
use std::collections::HashSet;

//Given the sum {}, return all possible Pythagorean triplets, which produce the said sum, or an empty HashSet if there are no such triplets. Note that you are expected to return triplets in [a, b, c] order, where a < b < c
pub fn find(sum: u32) -> HashSet<[u32; 3]> {
    // Euclid formula a = m2 -n2 ; b = 2mn; c = m2+n2 ;  m>n
    // and a+b+c  = m2 - n2 +2mn + m2 +n2 = 2m2 + 2mn = 2(m2+mn)
    let mut sol = HashSet::new();
    let max = (sum as f32).sqrt() as u32;
    for n in 1..=max {
        for m in n + 1..=max {
            let mut a = m * m - n * n;
            let mut b = 2 * m * n;
            let mut c = m * m + n * n;
            let s = a + b + c;
            // need to check also for non primitive triplets
            if sum % s == 0 {
                let k = sum / s;
                a = k * a;
                b = k * b;
                c = k * c;
                if a < b {
                    sol.insert([a, b, c]);
                } else {
                    sol.insert([b, a, c]);
                }
            }
        }
    }
    sol
}

Community comments

Find this solution interesting? Ask the author a question to learn more.

izderadicka's Reflection

Using Euklid's formula to generate triplets so it's much faster then naive iteration over a an b, but still significantly slower (~50x) then best solution :-(