aboutsummaryrefslogtreecommitdiff
path: root/rust/difference-of-squares/src/lib.rs
blob: 45997339f3d83edd8322bf8e89a2c7dfa365dea6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/// Implements square of Gauss' formula
pub fn square_of_sum(n: u32) -> u32 {
    (n * (n + 1) / 2).pow(2)
}

/// Implements the formula reported in Wolfram|Alpha at this
/// [link](https://www.wolframalpha.com/input/?i=sum+of+squares&assumption=%7B%22F%22%2C+%22SumOfSquaresOfIntegers%22%2C+%22sumlowerlimit%22%7D+-%3E%221%22&assumption=%7B%22F%22%2C+%22SumOfSquaresOfIntegers%22%2C+%22sumupperlimit2%22%7D+-%3E%22n%22)
pub fn sum_of_squares(n: u32) -> u32 {
    n * (1 + n) * (1 + 2 * n) / 6
}

pub fn difference(n: u32) -> u32 {
    square_of_sum(n) - sum_of_squares(n)
}