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.
functionsumSquareDifference(min,max){letsumOfSquares=0;letsquareOfSums=0;for(i=min;i<max+1;i++){sumOfSquares+=i**2;squareOfSums+=i;}return(squareOfSums**2)-sumOfSquares;}conststartTime=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
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.
defchallenge():sumOfSquares=0squareOfSums=0difference=0foriinrange(101):sumOfSquares+=i**2squareOfSums+=isquareOfSums=squareOfSums**2difference=squareOfSums-sumOfSquaresprint("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
// 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
// func SumSquareDifference receives the max range// and returns the difference of the sumSquare and the squareSum.funcSumSquareDifference(xint)int{sum:=0sumSquare:=0fori:=1;i<=x;i++{sum+=isumSquare+=i*i}squareSum:=sum*sumreturnsquareSum-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.
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;
}
funcsumSquareDifference(range:Int)->Int{varsumOfSquares=0varsquareOfSum=0fornumberin1..<range+1{//Is there a better way? Other than range+1?sumOfSquares+=(number*number)squareOfSum+=number}squareOfSum=squareOfSum*squareOfSumreturn(squareOfSum-sumOfSquares)}print(sumSquareDifference(range:100))
public class ProjectEuler{
static int n = 100;
public static void main(String []args){
System.out.println(differencehelper());
}
static int sumsquare(int n){
int sum = 0 ;
sum = (n*(n+1)(2*n+1))/6;
return sum;
}
static int squaresum(int n){
int sum = 0;
sum = (n(n+1))/2;
return (sum *sum);
}
static int differencehelper(){
return squaresum(n) - sumsquare(n);
}
}
Easy Java Solution using Gauss' Formula Hope you liked it ;)
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
Problem 6
The sum of the squares of the first ten natural numbers is,
12+22+...+102=385
The square of the sum of the first ten natural numbers is,
(1+2+...+10)2=552=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.*/
include
using namespace std;
int square_sum(int s);
int main()
{
int limit=100 ,sum=0 ,sumQ=0;
for(int i=1;i<=limit;i++)
{
sumQ=sumQ+(i*i);
sum =sum+i;
}
cout<<"the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum is \n ";
cout<< square_sum(sum)-sumQ ; // without function : cout<<sum*sum-sumQ
return 0;
}
int square_sum(int s)
{
return s*s;
}
Output >> 25164150
19 yo student *and* a full-time developer.
Building with Rails currently, exploring new frontiers.
I enjoy functional programming, Linux, FOSS, refactoring and mentoring :)
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
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.
Definitely highlights the need for maths in software development.
Woah, alright, you win 😲.
Also, there's a guide here to embed code and images in markdown (what dev.to uses).
thanks, I'm going to check it.
Python!
I surrender!
Ruby:
Ruby is so elegant 😍
Javascript !
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.
Yeah, also the fact that I'm iterating 2 times the same array !
Here is my nodejs solution
output
Yours performs faster than the one I submitted, and still looks nice, well done !
EDIT: some of the
lets could be replaced withconstthough 🙈true
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.
:)
Rust Solution: Playground
My take on this problem in python:
Output:
Some fun!
Benchmark result:
Rust
Go
goplay.space/#rQ0XekiCknZ
You can see the complete program on the playground link.
Here is my Javascript Solution
Ruby 2.7
Swift:
public class ProjectEuler{
static int n = 100;
public static void main(String []args){
System.out.println(differencehelper());
}
Easy Java Solution using Gauss' Formula Hope you liked it ;)
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
my code with C++
/*Sum square difference
Problem 6
The sum of the squares of the first ten natural numbers is,
12+22+...+102=385
The square of the sum of the first ten natural numbers is,
(1+2+...+10)2=552=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.*/
include
using namespace std;
int square_sum(int s);
int main()
{
int limit=100 ,sum=0 ,sumQ=0;
for(int i=1;i<=limit;i++)
{
sumQ=sumQ+(i*i);
sum =sum+i;
}
}
int square_sum(int s)
{
return s*s;
}
Output >> 25164150
not bad)))
new_list = []
for i in range (1,101):
new_list.append(i^2)
a = sum(new_list)
b = sum(range(1,101))^2
print(b-a)
new_list = []
for i in range (1,101):
new_list.append(i*2)
a = sum(new_list)
b = sum(range(1,101))*2
print(b-a)
Elixir: