平方差-Difference Of Squares

1. Readme

平方差

求,前n个自然数的和平方,与,平方和,之间的差值.

例如:

前十个自然数之和的平方为:

  • (1 + 2 + ... + 10)² = 55² = 3025.

前十个自然数的平方和为:

  • 1² + 2² + ... + 10² = 385.

因此,前十个自然数之和的平方,和,前十个自然数之和的平方之差是:

  • 3025 - 385 = 2640.

Source

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

2. 开始你的表演

pub fn square_of_sum(n: u32) -> u32 {
   unimplemented!("square of sum of 1...{}", n)
}

pub fn sum_of_squares(n: u32) -> u32 {
   unimplemented!("sum of squares of 1...{}", n)
}

pub fn difference(n: u32) -> u32 {
   unimplemented!(
       "difference between square of sum of 1...{n} and sum of squares of 1...{n}",
       n = n,
   )
}

3. 测试代码查看


# #![allow(unused_variables)]
#fn main() {
#[test]
fn test_square_of_sum_1() {
   assert_eq!(1, square_of_sum(1));
}

#[test]
//#[ignore]
fn test_square_of_sum_5() {
   assert_eq!(225, square_of_sum(5));
}

#[test]
//#[ignore]
fn test_square_of_sum_100() {
   assert_eq!(25502500, square_of_sum(100));
}

#[test]
//#[ignore]
fn test_sum_of_squares_1() {
   assert_eq!(1, sum_of_squares(1));
}

#[test]
//#[ignore]
fn test_sum_of_squares_5() {
   assert_eq!(55, sum_of_squares(5));
}

#[test]
//#[ignore]
fn test_sum_of_squares_100() {
   assert_eq!(338350, sum_of_squares(100));
}

#[test]
//#[ignore]
fn test_difference_1() {
   assert_eq!(0, difference(1));
}

#[test]
//#[ignore]
fn test_difference_5() {
   assert_eq!(170, difference(5));
}

#[test]
//#[ignore]
fn test_difference_100() {
   assert_eq!(25164150, difference(100));
}

#}

4. 答案


# #![allow(unused_variables)]
#fn main() {
pub fn square_of_sum(n: u32) -> u32 {
   let sum = n * (n + 1) / 2;
   sum * sum
}

pub fn sum_of_squares(n: u32) -> u32 {
   (0..n + 1).map(|x| x * x).fold(0, |accum, x| accum + x)
}

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

#}



填充/相关