// with for loopfuncsumSqDiffLoop(nint)int{varsOsqintvarsOtsintfori:=1;i<=100;i++{sOsq+=i*isOts+=i}return(sOts*sOts)-sOsq}// no loop - thanks to @lmbarr for his solutionfuncsumSqDiffNoLoop(nint)int{return(((n*n)*((n+1)*(n+1)))/4)-(n*(n+1)*(2*n+1)/6)}// Let's make some benchmarks!import"testing"funcBenchmarkSumSquareDiff(b*testing.B){benchs:=[]struct{namestringfunfunc(int)int}{{"Sum Square Diff Loop",sumSqDiffLoop},{"Sum Square Diff no Loop",sumSqDiffNoLoop},}// Let's test it with 1000 instead of 100 :Dinput:=1000for_,bench:=rangebenchs{b.Run(bench.name,func(b*testing.B){fori:=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
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Some fun!
Benchmark result: