DEV Community

Discussion on: Project Euler #6 - Sum Square Difference

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