views:

523

answers:

19

I take no credit for this challenge at all. It's Project Euler problem 6:

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.

I became interested in some code golfing here when I noticed my solution (in Python) was very, very short. I want to see how some other languages (perl, I'm looking at you!) can bring it in this simple problem.

So, what is the shortest possible way to solve this problem? Shortest means fewest characters in source code.

NOTE: bonus points for solving for the first n natural numbers.

+8  A: 

40/49 43 characters; should work in most languages

n=100;(n*(n+1)/2)**2-n*(n+1)*(2*n+1)/6;

Should work in some languages;

n=100;n*(n+1)*n*(n+1)/4-n*(n+1)*(2*n+1)/6;

This should work in most of the languages.

Note that 1^2 + 2^2 + ... + n^2 = n(n+1)(2n+1)/6 and 1 + 2 + ... + n = n(n+1)/2

EDIT: oh and for the bonus you just remove the first 6 chracters.

Gabi Purcaru
please, there is a typo in the note for the formula of sum of squares: the denominator should be 6.
Alex. S.
you are right; fixed
Gabi Purcaru
That was exactly my solution. Note that for the second, you can save a bit (6 characters) by moving the `/2` out: `n=100;n*(n+1)*n*(n+1)/4-n*(n+1)*(2*n+1)/6`
poke
Applying some algebra to this gets you down to 17 characters, see my answer.
Tim Goodman
+1  A: 

C#

Math.Pow(Enumerable.Range(1, 100).Sum(), 2)-
Enumerable.Range(1, 100).Select(i => i*i).Sum()
ohadsc
A: 

Mine was also short...

def euler6(limit):
    """
    calculate the difference between the sum of the squares of
    the first n natural numbers and the square of the sum of
    the same n natural numbers.

      >>> euler6(10)
      2640


    """
    sequence = range(limit+1)
    squares = sum(map(lambda x: x*x, sequence))
    sums = sum(sequence)
    sums *= sums
    return sums-squares
TokenMacGuy
A: 
import numpy
v = numpy.arange(100)
print sum(v)**2 - sum(v*v)
Winston Ewert
+1  A: 

Python 2.x, 48 characters

a=range(n+1)
print sum(a)**2-sum(x*x for x in a)

I originally wrote it in Python 3.x, which is 49 characters:

a=range(n+1)
print(sum(a)**2-sum(x*x for x in a))
Rafe Kettler
+4  A: 

Perl 15 chars:

 print 25164150;
Motti
I don't know if I should upvote or downvote. :S
Matteo Italia
I remember participating in a programming competition where the winners hardcoded answers for one of the problems. Technically it gave the correct output so they were awarded full points xD
Colin O'Dell
cat 8 chars: 25164150
Winston Ewert
@Matteo, in my defence I wrote this before the requirement to solve for `N` was added :o)
Motti
python 14 chars: print 25164150. Haha, bested.
Rafe Kettler
@Rafe Kettler: `say 25164150;`: 13 characters, thanks.
Daenyth
Semi column isn't needed, so 12 chars : say 25164150
M42
@Daenyth: PHP - `?>25164150`
mattbasta
+4  A: 

Octave: 28 chars

v=1:100;sum(v)**2-sum(v.*v)
Winston Ewert
+5  A: 

Since the "intelligent" solution (that comes from two simple math proofs) has been already posted by @Gabi Purcaru and short solutions for such problem are easy, instead I'll post a long solution based on template metaprogramming, I don't think it's so easy to make it longer without putting in useless garbage/whitespace/....

C++ - 648 659 chars

#include <iostream>

template<int Num>
struct Square
{
    static const int Value = Num*Num;
};

template<int Num>
struct NatSum
{
    static const int Value=Num+NatSum<Num-1>::Value;
};

template<>
struct NatSum<0>
{
    static const int Value = 0;
};

template<int Num>
struct SquaresSum
{
    static const int Value=Square<Num>::Value+SquaresSum<Num-1>::Value;
};

template<>
struct SquaresSum<0>
{
    static const int Value = 0;
};

template<int Num>
struct DifferenceOfSums
{
    static const int Value = Square<NatSum<Num>::Value>::Value - SquaresSum<Num>::Value;
};

int main()
{
    std::cout<<DifferenceOfSums<100>::Value<<std::endl;
    return 0;
}

Now enjoy your challenge result calculated at compile time and put directly in the executable. :)

Matteo Italia
meh... I know why there aren't gode golfs for longest answers.. :P Btw. is anyone thinking this is more readable than a golfed version?
poke
@Poke: Maybe in C++ it is.
Rafe Kettler
Wonderful and it's the fastest one too! (For runtime anyway, not compile time).
Motti
+2  A: 

Mathematica 17 chars: After applying FullSimplify

n(n^2-1)(3n+2)/12

Mathematica 27 chars: As it doesn't require those pesky multiplication symbols...

(n(n+1))^2/4-n(n+1)(2n+1)/6

Or in vector form, Mathematica 2825 chars: after reviewing the other Mathematica answer, I was able to shave off another 3 chars

Plus@@#^2-#.#&@Range[100]
rcollyer
I love how the syntax highlighting feature doesn't even recognize most of your code as real code.
Rafe Kettler
Yes. It is very easy to write line noise in Mathematica.
Eric Towers
And perl isn't line noise?
rcollyer
+1 #.# is nice :)
belisarius
belisarius
A: 
Eric Towers
+9  A: 

Almost Any Language: 20 chars.

(n*n-1)*(3*n+2)*n/12
Eamon Nerbonne
+2  A: 

17 or 18 characters

(3n/2+1)(n^3-n)/6
(3n/2+1)(n**3-n)/6

depending on how your language does exponents

Edit: well, 20 characters (3*n/2+1)*(n**3-n)/6 if your language doesn't understand implicit multiplication... but Mathematica does.

Tim Goodman
Also needs exponentiation, which many languages don't have...
Eamon Nerbonne
Easy enough to do without exponents, simply expand the exponent for a cost of an additional 2 chars `n^3` == `n*n*n`.
jball
+1  A: 

J, 19 characters

(12%~]*<:@*:*2+3*])

This just calculates n(n^2-1)(3n+2)/12.

J, 21 characters

(([:*:+/)-[:+/*:)i.>:

This actually generates the list of natural numbers up to N (i.>:), then calculates the sum of squares [:*:+/ and square of sums [:+/*:, then subtracts them.

David
+1  A: 

Haskell - 33 chars

g x=sum.map(\y->(y-1)*y*y)$[2..x]

edit:

To make a full program we need 79 chars

import System
main=getArgs>>=print.(\x->sum.map(\y->(y-1)*y*y)$[2..x]).read.head
Marc
A: 

Perl, 41 Chars

This is a 'proper' attempt.

Code: $c+=$_**2,$e+=$_ for 0..pop;print$e**2-$c

Usage:

$ perl -e '$c+=$_**2,$e+=$_ for 0..pop;print$e**2-$c' 100
25164150
Zaid
A: 

Golfscript - 17 chars

~:).*(3)*2+*)*12/

Reads number from stdin\

23 chars to generate the first 100

100,{:).*(3)*2+*)*12/}%
gnibbler
A: 

Mathematica 8 chars

"My In is your Out"

  In> 25164150
  Out> 25164150

25164150 is a full valid Mathematica expression that can be evaluated on its own.

belisarius
+2  A: 

Mathematica "Guessing the Answer"

Mathematica is able to "guess" the function that generates some sequences.

So, If you calculate the first six terms for this problem, the result is:

 {0, 4, 22, 70, 170, 350}  

Now we can enter that sequence to the "sequences oracle", and get the function:

FindSequenceFunction[{0, 4, 22, 70, 170, 350}]

Mathematica answers:

1/12 (#-1) (2 # + 5 #^2 + 3 #^3) &  

which is the formula posted anywhere in the other answers.

So we can calculate the 100th term using the first six terms ... without knowing how to generate them!

In> FindSequenceFunction[{0, 4, 22, 70, 170, 350}][100]
Out> 25164150    
belisarius
+1, I had no idea that function existed.
rcollyer
A: 

Oracle SQL - 82 chars

select sum(l)*sum(l)-sum(l*l) from (select level l from dual connect by level<=:n)
Mark Bannister