Problem 6 "Sum square difference"

The sum of the squares of the first ten natural numbers is,

$$1^2 + 2^2 + ... + 10^2 = 385$$

The square of the sum of the first ten natural numbers is,

$$(1 + 2 + ... + 10)^2 = 55^2 = 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.

問 6 「二乗和の差」

最初の10個の自然数について, その二乗の和は,

$$1^2 + 2^2 + ... + 10^2 = 385$$

最初の10個の自然数について, その和の二乗は,

$$(1 + 2 + ... + 10)^2 = 55^2 = 3025$$

これらの数の差は 3025 - 385 = 2640 となる.

同様にして, 最初の100個の自然数について二乗の和と和の二乗の差を求めよ.

struct Sequence {
    n: u64,
}

impl Sequence {
    fn sum_of_squares(&self) -> u64 {
        self.n * (self.n + 1) * (2 * self.n + 1) / 6
    }
    fn sum(&self) -> u64 {
        (1 + self.n) * self.n / 2
    }
}

fn main() {
    let s = Sequence{n: 100};
    let sum = s.sum();
    let diff = sum * sum - s.sum_of_squares();

    println!("{}", diff);
    assert_eq!(diff, 25164150);
}
package main

import "fmt"

type Sequence struct {
	n uint64
}

func (s *Sequence) sumOfSquares() uint64 {
	return s.n * (s.n + 1) * (2*s.n + 1) / 6
}

func (s *Sequence) sum() uint64 {
	return (1 + s.n) * s.n / 2
}

func Example() {
	s := Sequence{n: 100}
	sum := s.sum()
	diff := sum*sum - s.sumOfSquares()
	fmt.Println(diff)
	// Output: 25164150
}
→ Go playground
function assert(condition: any, msg?: string): asserts condition {
  if (!condition) {
    throw new Error(msg);
  }
}

interface Sequence {
  n: number;
}

function sumOfSquares(s: Sequence): number {
  return s.n * (s.n + 1) * (2 * s.n + 1) / 6;
}

function sum(s: Sequence): number {
  return (1 + s.n) * s.n / 2;
}

const s: Sequence = { n: 100 };
const su = sum(s);
const diff = su * su - sumOfSquares(s);
console.log(diff);
assert(diff === 25164150);
→ TypeScript playground