DEV Community

Peter Kim Frank
Peter Kim Frank

Posted on

Project Euler #6 - Sum Square Difference

Continuing the wonderful community solutions to Project Euler.

This is Problem 6, sum square difference.

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

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

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

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

Top comments (31)

Collapse
 
lmbarr profile image
Luis Miguel • Edited

no loops!

python3

def sum_square_difference(n):
      return (((n**2) * (n + 1)**2) / 4) - (n * (n + 1) * (2*n + 1) / 6)

print(sum_square_difference(100))

I dont know why when I tried to upload images they dont appear

Collapse
 
maxart2501 profile image
Massimo Artizzu

Aw yeah 👌

If some are wondering, that comes from well-known formulas for the sum of the first n integers and n squares. There's a generalization, too, but also a pretty common formula for the first n cubes.

A solid mathematical approach can really simplify programming challenges. It almost feels like cheating.

Collapse
 
natonathan profile image
Nathan Tamez

Definitely highlights the need for maths in software development.

Collapse
 
badrecordlength profile image
Henry 👨‍💻

Woah, alright, you win 😲.
Also, there's a guide here to embed code and images in markdown (what dev.to uses).

Collapse
 
lmbarr profile image
Luis Miguel

thanks, I'm going to check it.

Collapse
 
aspittel profile image
Ali Spittel • Edited

Python!

def sum_square_difference(n):
    numbers = range(1, n+1)
    sum_squares = sum(i**2 for i in numbers)
    square_sum = sum(numbers)**2
    return square_sum - sum_squares

print(sum_square_difference(100))
Collapse
 
flrnd profile image
Florian Rand

I surrender!

Collapse
 
sabatesduran profile image
Dídac • Edited

Ruby:

def sum_square_difference(n)
  numbers = (1..n)
  square_of_sum = numbers.sum ** 2
  sum_of_square = numbers.map { |n| n ** 2 }.sum
  square_of_sum - sum_of_square
end

puts sum_square_difference(10)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
nans profile image
Nans Dumortier

Ruby is so elegant 😍

Collapse
 
nans profile image
Nans Dumortier

Javascript !

const sumSquareDifference = (n) => {
  const numbers = [...Array(n + 1).keys()];
  const sumOfSquares = numbers.reduce((accumulator, number) => accumulator + (number ** 2));
  const squareOfSum = numbers.reduce((accumulator, number) => accumulator + number) ** 2;
  return squareOfSum - sumOfSquares;
}
console.log(sumSquareDifference(10));
Collapse
 
natonathan profile image
Nathan Tamez

Yours is good. But I have a feeling it uses more then one for/for each loop. May explain why it is a bit slower then mine. Not sure.

Collapse
 
nans profile image
Nans Dumortier

Yeah, also the fact that I'm iterating 2 times the same array !

Collapse
 
natonathan profile image
Nathan Tamez • Edited

Here is my nodejs solution

function sumSquareDifference(min, max) {
    let sumOfSquares = 0;
    let squareOfSums = 0;
    for (i = min; i < max + 1; i++) {
        sumOfSquares += i ** 2;
        squareOfSums += i;
    }

    return (squareOfSums ** 2) - sumOfSquares;
}
const startTime = Date.now();
console.log(`The difference between the sum of the squares of the first one
 hundred natural numbers and the square of the sum,
is ${sumSquareDifference(1, 100)}`);
console.log(`Time Taken: ${Math.round(Date.now() - startTime)}ms`);

output

The difference between the sum of the squares of the first one hundred natural numbers and the square of the sum,is 25164150
Time Taken: 2ms
Collapse
 
nans profile image
Nans Dumortier • Edited

Yours performs faster than the one I submitted, and still looks nice, well done !

EDIT: some of the lets could be replaced with const though 🙈

Collapse
 
natonathan profile image
Nathan Tamez

true

Collapse
 
olivierpicault profile image
Olivier Picault

From ProjectEuler:

Please do not deprive others of going through the same process by publishing your solution outside of Project Euler; for example, on other websites, forums, blogs, or any public repositories (e.g. GitHub), et cetera. Members found to be spoiling problems will have their accounts locked.

:)

Collapse
 
jay profile image
Jay

Rust Solution: Playground

fn main() {
    println!("{}", get_difference(100));
}

fn get_difference(end: usize) -> u32 {
    ((1..=end).sum::<usize>().pow(2) - (1..=end).map(|n| n.pow(2)).sum::<usize>()) as u32
}
Collapse
 
badrecordlength profile image
Henry 👨‍💻

My take on this problem in python:

def challenge():
    sumOfSquares = 0
    squareOfSums = 0
    difference = 0
    for i in range(101):
        sumOfSquares += i ** 2
        squareOfSums += i
    squareOfSums = squareOfSums ** 2
    difference =  squareOfSums - sumOfSquares
    print("The difference between the sum of squares and the square of sums up to 100 is {}".format(difference))

Output:

The difference between the sum of squares and the square of sums up to 100 is 25164150
Collapse
 
crownedprinz profile image
Ademola John • Edited

Here is my Javascript Solution


function sumSquareDifference(n) {
  // Good luck!
  let a = 0,b=0,c=0;
  for(let i = 1;i<=n;i++){
    a+= (Math.pow(i,2));
    b+=i
  }
c=Math.pow(b,2)-a

console.log(a);
console.log(b);
  return c;
}
Collapse
 
kip13 profile image
kip • Edited

Rust

fn get_sum_square_difference(end: usize) -> usize {
    let mut sum: usize = 0;
    let square_sum = (1..=end).fold(0usize, |fin, num| { sum += num; fin + num.pow(2) });

    sum.pow(2) - square_sum
}
Collapse
 
comaldave profile image
David Skinner

Go Gopher

goplay.space/#rQ0XekiCknZ

// func SumSquareDifference receives the max range
// and returns the difference of the sumSquare and the squareSum.
func SumSquareDifference(x int) int {
    sum := 0
    sumSquare := 0

    for i := 1; i <= x; i++ {
        sum += i
        sumSquare += i * i
    }

    squareSum := sum * sum

    return squareSum - sumSquare
}

You can see the complete program on the playground link.

  • I have included a block that confirms that my function provides the expected response.
  • I then start a timer so I can print the elapsed time to run the function.
  • After printing the results, I include a comment defining the Output, If the output changes it will generate an error on my computer.
  • The language is Go but it is more a C++ style, I am not the best Go programmer.
  • Code needs to be readable, compilers can do the optimization.
Collapse
 
flrnd profile image
Florian Rand • Edited

Some fun!

// with for loop
func sumSqDiffLoop(n int) int {
    var sOsq int
    var sOts int
    for i := 1; i <= 100; i++ {
        sOsq += i * i
        sOts += i
    }
    return (sOts * sOts) - sOsq
}
// no loop - thanks to @lmbarr for his solution
func sumSqDiffNoLoop(n int) int {
    return (((n * n) * ((n + 1) * (n + 1))) / 4) - (n * (n + 1) * (2*n + 1) / 6)
}

// Let's make some benchmarks!

import "testing"

func BenchmarkSumSquareDiff(b *testing.B) {
    benchs := []struct {
        name string
        fun  func(int) int
    }{
        {"Sum Square Diff Loop", sumSqDiffLoop},
        {"Sum Square Diff no Loop", sumSqDiffNoLoop},
    }
        // Let's test it with 1000 instead of 100 :D
    input := 1000

    for _, bench := range benchs {
        b.Run(bench.name, func(b *testing.B) {
            for i := 0; i < b.N; i++ {
                bench.fun(input)
            }
        })
    }
}

Benchmark result:

❯ go test -bench=.

goos: linux
goarch: amd64
/Sum_Square_Diff_Loop-4             20000000          62.7 ns/op
/Sum_Square_Diff_no_Loop-4          500000000         3.58 ns/op
PASS
ok      _/h/f/s/g/src/project-euler/06  3.474s
Collapse
 
fossilizeddev profile image
Carlos E. Barboza • Edited

Swift:

func sumSquareDifference(range: Int) -> Int {
    var sumOfSquares = 0
    var squareOfSum = 0
    for number in 1..<range+1 { //Is there a better way? Other than range+1?
        sumOfSquares += (number*number)
        squareOfSum += number
    }
    squareOfSum = squareOfSum*squareOfSum
    return (squareOfSum - sumOfSquares)
}

print(sumSquareDifference(range:100))
Collapse
 
hanachin profile image
Seiei Miyagi

Ruby 2.7

p (1..100).then { @1.sum ** 2 - @1.sum { @1 ** 2 } }
Collapse
 
hishamkhr profile image
hishamkhr

hi
i try this:
sum of numbers= n(n+1)/2
then i get the square.
after that i found an equation about sum of squares:
(2*n^3 +3*n^2+n )/6
but i didn't get right result !!!!
so where i lost the control ?
thanks