2018-2-14

Project Euler number six solved with Rust

Solved by taking the 100th triangular number minus a 2000-year-old formula by Archimedes.

The sixth Project Euler problem - Sum Square Difference - is stated as follows.

The sum of the squares of the first ten natural numbers is 385. The square of the sum of the first ten natural numbers is 3025. Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

fn sum_square_difference(n: u32) -> u32 {
    (n*(n+1)/2).pow(2) - ((n*(n+1)*(2*n+1))/6)
}

fn main() {
    let n = 100;
    println!(
        "The difference is {} with n = {}.",
        sum_square_difference(n),
        n,
    );
}
Jan Järfalk — User experienced esthete, technician, geek and web worker. Aspiring artist and recreational mathematician. I indulge and travel plenty. Constraints are good.