开发者

Difference of sums

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, 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 开发者_StackOverflow中文版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.


Almost Any Language: 20 chars.

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


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.


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. :)


Perl 15 chars:

 print 25164150;


Octave: 28 chars

v=1:100;sum(v)**2-sum(v.*v)


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    


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.


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.


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]


C#

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


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))


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


Golfscript - 17 chars

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

Reads number from stdin\

23 chars to generate the first 100

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


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


import numpy
v = numpy.arange(100)
print sum(v)**2 - sum(v*v)


Mathematica: brute force (39 chars, 6 removable):

    Plus@@# ^2 - Plus@@ (#^2) &@ Range[100]

by means of math, on the fly (70 chars, 24 removable -- we don't have to simplify, specify lower limits, or use a 3 character function name):

    In[1]:= foo[k_] = Simplify[Sum[n, {n, 1, k}]^2 - Sum[n^2, {n, 1, k}]]
            foo[100]
    Out[1]= 1/12 k (-2 - 3 k + 2 k^2 + 3 k^3)
    Out[2]= 25164150

by means of previously performed math (40 chars, 11 removable)

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

How short this can be depends on how much prior computation we permit.


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


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.


Oracle SQL - 82 chars

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


Here is solution in a C *cheers*

#include <stdio.h>
#include <stdlib.h>
//Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
int main()
{
   int sum1=0,sum2=0,psum=0;

   for(int i=1;i<=100;i++)
   sum1+=i*i;

   for(int i=1;i<=100;i++)
   psum+=i;
   sum2=psum*psum;

   printf("\nDifference is: %d\n",sum2-sum1);


}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜