Difference of the square of the sum

37

6

Find the difference between the square of the sums and sum of the squares.

This is the mathematical representation:

\$\left(\sum n\right)^2-\sum n^2\$

Your program/method should take two inputs, these are your lower and upper limits of the range, and are inclusive. Limits will be whole integers above 0.

Your program/method should return the answer.

You may use whichever base you would like to, but please state in your answer which base you have used.

Test case (Base 10)

5,9      970
91,123   12087152
1,10     2640

This is usual code-golf, so the shorter the answer the better.

george

Posted 2016-06-20T13:53:40.917

Reputation: 1 495

11It took me a while to realize the input was the endpoints of a range. – Brad Gilbert b2gills – 2016-06-20T14:08:24.203

@BradGilbertb2gills edited for clarity – george – 2016-06-20T14:20:09.973

This is simpler than it looks ? – cat – 2016-06-22T20:17:42.853

@cat what do you mean by that? Yes the maths is simple Alevel stuff. But it's all down to how you golf it – george – 2016-06-22T20:18:59.837

@george The question and many of the answers make it look like a lot of work, but it's not

– cat – 2016-06-22T21:17:08.430

@cat I never said it was a lot of work. As I mentioned above, it is simple Alevel mathematics. – george – 2016-06-22T21:18:40.597

I assume not, but may we take an array as input instead of the start and end points? – caird coinheringaahing – 2018-04-13T18:42:50.897

@cairdcoinheringaahing amazing that people are still going at it a year and half later. When I wrote it I said two inputs, so in theory you could pass two arrays as input, but it must be two. Not one away with both inputs. Although I’d be interested to see both solutions – george – 2018-04-13T20:23:16.003

Answers

23

Python 2, 43 bytes

f=lambda a,b,s=0:b/a and 2*a*s+f(a+1,b,s+a)

Test it on Ideone.

How it works

Call the function defined in the specification g(a, b). We have that

Define the function f(x, y, s) recursively as follows.

By applying the recurrence relation of f(a, b, 0) a total of b - a times, we can show that.

This is the function f of the implementation. While b/a returns a non-zero integer, the code following and is executed, thus implementing the recursive definition of f.

Once b/a reaches 0, we have that b > a and the lambda returns False = 0, thus implementing the base case of the definition of f.

Dennis

Posted 2016-06-20T13:53:40.917

Reputation: 196 637

ah okay. Could you explain your method though? – george – 2016-06-20T18:33:50.417

I will, but I'm currently trying to golf it a bit more. – Dennis – 2016-06-20T18:34:11.850

thanks for the formula. I guess I never saw it like that because we don't cover sums of series like that at school. Pretty interesting though! – george – 2016-06-20T21:27:39.383

2@george I've finished the explanation. – Dennis – 2016-06-20T22:53:15.660

Wanna tell us a bit more of how in the world the idea to define f came into your mind! The motivation! I'm genuinely interested. – Musa Al-hassy – 2016-06-22T14:11:16.440

15

MATL, 9 bytes

&:&*XRssE

Try it online!

Explanation

&:   % Inclusive range between the two implicit inputs
&*   % Matrix of all pair-wise products
XR   % Upper triangular part of matrix, without the diagonal
ss   % Sum of all elements of the matrix
E    % Multiply by 2. Implicit display

Example

These are the partial results of each line for inputs 5 and 9:

  1. &:

    5 6 7 8 9
    
  2. &:&*

    25 30 35 40 45
    30 36 42 48 54
    35 42 49 56 63
    40 48 56 64 72
    45 54 63 72 81
    
  3. &:&*XR

    0 30 35 40 45
    0  0 42 48 54
    0  0  0 56 63
    0  0  0  0 72
    0  0  0  0  0
    
  4. &:&*XRss

    485
    
  5. &:&*XRssE

    970
    

Luis Mendo

Posted 2016-06-20T13:53:40.917

Reputation: 87 464

7I really like seeing the partial results. They really help with understanding the program. Thanks for including them! – DanTheMan – 2016-06-20T21:54:26.097

10

Jelly, 9 8 bytes

rµS²_²S$

Try it online!

r         inclusive range from first input to second input
 µ        pass the range to a new monadic chain
  S       the sum
   ²      squared
    _     minus...
     ²S$  the squares summed

Thanks to FryAmTheEggman for a byte!

Doorknob

Posted 2016-06-20T13:53:40.917

Reputation: 68 138

3For once, Jelly is actually very readable. – Adám – 2016-06-20T14:22:34.760

Can I fork this to my answer? – Leaky Nun – 2016-06-20T15:08:20.280

@LeakyNun what does that mean? – Doorknob – 2016-06-20T15:17:12.363

This. – Leaky Nun – 2016-06-20T15:21:57.173

6Nice earrings: S²_²S – Thomas Weller – 2016-06-20T18:22:25.080

10

Python 2, 45 bytes

lambda a,b:(a+~b)*(a-b)*(3*(a+b)**2+a-b-2)/12

Closed form solution - not the shortest, but I thought it'd be worth posting anyway.

Explanation

Let p(n) be the nth square pyramidal number, and t(n) be the nth triangular number. Then, for n over the range a, ..., b:

  • ∑n = t(b)-t(a-1), and
  • ∑n² = p(b) - p(a-1)
  • So (∑n)²-∑n² = (t(b)-t(a-1))² - (p(b) - p(a-1)).

This expression reduces to that in the code.

Sp3000

Posted 2016-06-20T13:53:40.917

Reputation: 58 729

Hi could you explain your equation if possible. My python version is 16 bytes longer and I can't figure out how you derived your equation – george – 2016-06-20T15:06:06.297

1

@george Let p(n) be the nth square pyramidal number, and t(n) be the nth triangular number. Then this is a simplified version of (t(b)-t(a-1))^2 - (p(b) - p(a-1)).

– Martin Ender – 2016-06-20T15:11:49.990

@MartinEnder So that is the exact formula that I have used, but Sp3000 has simplified it in a way that I cannot understand. My python script is: (b-~b-a~-a)*2/4-(b-~b(2b+1)-a~-a(2*a-1))/6 if that is of any use. I have golfed as much as I can the two formula – george – 2016-06-20T15:15:37.820

@george Sometimes, with problems like these, the easiest way is to get Wolfram|Alpha to do the tedious part, then double checking to make sure it's right. To be honest, I don't think I could have pulled the (a-b-1) factor out of (b*(b+1)*(2b+1)-a*(a-1)*(2a-1))/6 on my own.

– Sp3000 – 2016-06-21T00:16:34.057

@Sp3000 that's a great way to do it. I'll try that in future – george – 2016-06-21T05:17:08.603

6

05AB1E, 8 bytes

ŸDOnsnO-

Explained

ŸD       # range from a to b, duplicate
  On     # sum and square first range
    s    # swap top 2 elements
     nO  # square and sum 2nd range
       - # take difference

Try it online

Emigna

Posted 2016-06-20T13:53:40.917

Reputation: 50 798

Is 05AB1E a ROT13 version of Jelly maybe? Substitute r by Ÿ, µ by D, S by O, ² by n, _ by s and $ by -. – Thomas Weller – 2016-06-20T18:24:47.043

4@ThomasWeller: They are quite different actually. A common offset between some "functions" are most likely a coincident. Jelly is a tacit language about chaining functions (afaik), while 05AB1E is a stack based language. – Emigna – 2016-06-20T18:29:34.377

6

Mathematica, 21 bytes

Tr[x=Range@##]^2-x.x&

An unnamed function taking two arguments and returning the difference. Usage:

Tr[x=Range@##]^2-x.x&[91, 123]
(* 12087152 *)

There's three small (and fairly standard) golfing tricks here:

  • ## represents both arguments at once, so that we can use prefix notation for Range. Range@## is shorthand for Range[##] which expands to Range[a, b] and gives us an inclusive range as required.
  • Tr is for trace but using it on a vector simply sums that vector, saving three bytes over Total.
  • x.x is a dot product, saving four bytes over Tr[x^2].

Martin Ender

Posted 2016-06-20T13:53:40.917

Reputation: 184 808

Would Variance help? – Leaky Nun – 2016-06-20T14:51:52.490

@LeakyNun I don't see how, because one of the two terms in Variance is divided by n and the other by n^2 and I don't see an easy way to undo those separately. – Martin Ender – 2016-06-20T14:53:31.077

1Tr@#^2-#.#&@*Range is only 18 bytes. – Misha Lavrov – 2018-11-05T15:58:24.877

@MishaLavrov neat! Feel free to make it a separate answer. :) – Martin Ender – 2018-11-05T20:51:11.827

5

Labyrinth, 28 24 bytes

?:?:}+=-:(:(#{:**+**#2/!

Try it online!

Explanation

Since loops tend to be expensive in Labyrinth, I figured the explicit formula should be shortest, as it can be expressed as linear code.

Cmd Explanation                 Stacks [ Main | Aux ]
?   Read M.                     [ M | ]
:   Duplicate.                  [ M M | ]
?   Read N.                     [ M M N | ]
:   Duplicate.                  [ M M N N | ]
}   Move copy to aux.           [ M M N | N ]
+   Add.                        [ M (M+N) | N ]
=   Swap tops of stacks.        [ M N | (M+N) ]
-   Subtract.                   [ (M-N) | (M+N) ]
:   Duplicate.                  [ (M-N) (M-N) | (M+N) ]
(   Decrement.                  [ (M-N) (M-N-1) | (M+N) ]
:   Duplicate.                  [ (M-N) (M-N-1) (M-N-1) | (M+N) ]
(   Decrement.                  [ (M-N) (M-N-1) (M-N-2) | (M+N) ]
#   Push stack depth.           [ (M-N) (M-N-1) (M-N-2) 3 | (M+N) ]
{   Pull (M+N) over from aux.   [ (M-N) (M-N-1) (M-N-2) 3 (M+N) | ]
:   Duplicate.                  [ (M-N) (M-N-1) (M-N-2) 3 (M+N) (M+N) | ]
*   Multiply.                   [ (M-N) (M-N-1) (M-N-2) 3 ((M+N)^2) | ]
*   Multiply.                   [ (M-N) (M-N-1) (M-N-2) (3*(M+N)^2) | ]
+   Add.                        [ (M-N) (M-N-1) (3*(M+N)^2 + M - N - 2) | ]
*   Multiply.                   [ (M-N) ((M-N-1)*(3*(M+N)^2 + M - N - 2)) | ]
*   Multiply.                   [ ((M-N)*(M-N-1)*(3*(M+N)^2 + M - N - 2)) | ]
#   Push stack depth.           [ ((M-N)*(M-N-1)*(3*(M+N)^2 + M - N - 2)) 1 | ]
2   Multiply by 10, add 2.      [ ((M-N)*(M-N-1)*(3*(M+N)^2 + M - N - 2)) 12 | ]
/   Divide.                     [ ((M-N)*(M-N-1)*(3*(M+N)^2 + M - N - 2)/12) | ]
!   Print.                      [ | ]

The instruction pointer then hits a dead end and has to turn around. When it now encounters / it attempts a division by zero (since the bottom of the stack is implicitly filled with zeros), which terminates the program.

Martin Ender

Posted 2016-06-20T13:53:40.917

Reputation: 184 808

4

Haskell, 34 bytes

a#b=sum[a..b]^2-sum(map(^2)[a..b])

Usage example: 91 # 123 -> 12087152.

Nothing to explain.

nimi

Posted 2016-06-20T13:53:40.917

Reputation: 34 639

3

Perl 6,  36 32  31 bytes

{([+] $_=@_[0]..@_[1])²-[+] $_»²}
{([+] $_=$^a..$^b)²-[+] $_»²}
{[+]($_=$^a..$^b)²-[+] $_»²}

Test it

Explanation:

{ # bare block with placeholder parameters $a and $b

  [+](# reduce with &infix:<+>
      # create a range, and store it in $_
      $_ = $^a .. $^b
  )²
  -
  [+] # reduce with &infix:<+>
    # square each element of $_ ( possibly in parallel )
    $_»²
}

Test:

#! /usr/bin/env perl6
use v6.c;
use Test;

my @tests = (
  (5,9) => 970,
  (91,123) => 12087152,
  (1,10) => 2640,
);

plan +@tests;

my &diff-sq-of-sum = {[+]($_=$^a..$^b)²-[+] $_»²}

for @tests -> $_ ( :key(@input), :value($expected) ) {
  is diff-sq-of-sum(|@input), $expected, .gist
}
1..3
ok 1 - (5 9) => 970
ok 2 - (91 123) => 12087152
ok 3 - (1 10) => 2640

Brad Gilbert b2gills

Posted 2016-06-20T13:53:40.917

Reputation: 12 713

1Save a byte moving the assignment and evading parens: {$_=$^a..$^b;.sum²-[+] $_»²} – Phil H – 2018-07-02T10:39:12.353

125 bytes: {.sum²-[+] $_»²}o&[..] – nwellnhof – 2018-11-05T10:29:48.420

3

Matlab, 30 29 28 bytes

Using Suever's idea of norm gives us 2 bytes less

@(x,y)sum(x:y)^2-norm(x:y)^2

Old (simple) version:

@(x,y)sum(x:y)^2-sum((x:y).^2)

pajonk

Posted 2016-06-20T13:53:40.917

Reputation: 2 480

3

Octave, 27 23 bytes

@(x,y)sum(z=x:y)^2-z*z'

Creates an anonymous function named ans which accepts two inputs: ans(lower, upper)

Online Demo

Explanation

Creates a row vector from x to y (inclusive) and stores it in z. We then sum all the elements using sum and square it (^2). To compute the sum of the squares, we perform matrix multplication between the row-vector and it's transpose. This will effectively square each element and sum up the result. We then subtract the two.

Suever

Posted 2016-06-20T13:53:40.917

Reputation: 10 257

3

JavaScript (ES6), 50 37 bytes

f=(n,m,s=0)=>n>m?0:2*n*s+f(n+1,m,n+s)

Now a port of @Dennis♦'s Python solution.

Neil

Posted 2016-06-20T13:53:40.917

Reputation: 95 035

Try using n=>m=>eval(`for(s=t=0;n<=m;t+=n++)s+=n*n;t*t-s`) – Mama Fun Roll – 2016-06-21T15:24:39.853

@MamaFunRoll On the other hand, I could try porting Dennis♦'s Python solution... – Neil – 2016-06-22T12:49:27.353

3

Haskell, 36 bytes

m#n=sum[2*i*j|i<-[m..n],j<-[i+1..n]]

λ> m # n = sum [ 2*i*j | i <- [m..n], j <- [i+1..n] ]
λ> 5 # 9
970
λ> 91 # 123
12087152
λ> 1 # 10
2640

Note that

$$\left( \sum_{k=m}^n k \right)^2 - \sum_{k=m}^n k^2 = \cdots = \sum_{k_1=m}^n \sum_{k_2=m\\ k_2 \neq k_1}^n k_1 k_2 = \sum_{k_1=m}^n \sum_{k_2=k_1+1}^n 2 \,k_1 k_2$$

Rodrigo de Azevedo

Posted 2016-06-20T13:53:40.917

Reputation: 177

1You don't need the parens around i+1. – Post Rock Garf Hunter – 2018-07-02T02:50:13.720

2

Also if you want to talk Haskell and Haskell golfing you can join us in the chat room.

– Post Rock Garf Hunter – 2018-07-02T02:51:18.837

3

Java, 84 77 characters, 84 77 bytes

7 bytes smaller due to Martin Ender and FryAmTheEggMan, thank you.

public int a(int b,int c){int e=0,f=0;for(;b<=c;e+=b,f+=b*b++);return e*e-f;}

Using the three test cases in the original post: http://ideone.com/q9MZSZ

Ungolfed:

public int g(int b, int c) {
    int e = 0, f = 0;
    for (; b <= c; e += b, f += b * b++);
    return e*e-f;
}

Process is fairly self-explanatory. I declared two variables to represent the square of the sums and the sum of the squares and repeatedly incremented them appropiately. Finally, I return the computed difference.

Mario Ishac

Posted 2016-06-20T13:53:40.917

Reputation: 491

Welcome to PPCG! You can probably save a byte by putting that ++ on f+=b*b++ (so you can leave the third slot of the for empty) and you also don't need to square e before returning it (i.e. just do return e*e-f). – Martin Ender – 2016-06-20T18:32:55.340

Actually instead of leaving the third slot of the for empty, move the f+=b*b++ in there, so you can save on both a semicolon and the braces. – Martin Ender – 2016-06-20T18:34:06.557

Great catch @MartinEnder, thank you :) – Mario Ishac – 2016-06-20T18:51:51.797

Also based on what Martin had in mind, this seems to be a bit shorter.

– FryAmTheEggman – 2016-06-20T18:59:06.653

@FryAmTheEggman Oh, I wasn't aware that you could have multiple statements in the third slot of the for-loop, thanks to you as well. – Mario Ishac – 2016-06-20T19:01:54.160

1

Apparently, my last comment was incorrect. It is actually a special part of the Java grammar: the final statement of a for is actually a special kind of statement, which is called a statement expression list. This special statement can have more than one statement joined by a comma. See 14.14.1 (you'll have to navigate there yourself, I couldn't find a way to make a more precise link) of the language specification.

– FryAmTheEggman – 2016-06-20T19:38:27.343

You can also move e+=b outside for loop (http://ideone.com/2rgZSh). This will save you one more character

– User31689 – 2016-06-21T08:58:53.943

3

JavaScript (ES6), 46 bytes

f=(x,y,s=0,p=0)=>x<=y?f(x+1,y,s+x,p+x*x):s*s-p

Washington Guedes

Posted 2016-06-20T13:53:40.917

Reputation: 549

3

Factor, 48 bytes

[ [a,b] [ [ sq ] map sum ] [ sum sq ] bi - abs ]

An anonymous function.

[ 
  [a,b] ! a range from a to b 
  [ 
    [ sq ] map sum ! anonymous function: map sq over the range and sum the result 
  ] 
  [ sum sq ] ! the same thing, in reverse order
  bi - abs   ! apply both anon funcs to the range, subtract them and abs the result
]

cat

Posted 2016-06-20T13:53:40.917

Reputation: 4 989

2

Japt, 10 bytes

õV
x²aUx ²

Try it

Shaggy

Posted 2016-06-20T13:53:40.917

Reputation: 24 623

2

Brachylog, 24 bytes

:efL:{:2^.}a+S,L+:2^:S-.

Expects the 2 numbers in Input as a list, e.g. [91:123].

Explanation

:efL                     Find the list L of all integers in the range given in Input
    :{:2^.}a             Apply squaring to each element of that list
            +S,          Unify S with the sum of the elements of that list
               L+:2^     Sum the elements of L, then square the result
                    :S-. Unify the Output with that number minus S

Fatalize

Posted 2016-06-20T13:53:40.917

Reputation: 32 976

2

APL, 23 20 bytes

-/+/¨2*⍨{(+/⍵)⍵}⎕..⎕

Works in NARS2000.

Adám

Posted 2016-06-20T13:53:40.917

Reputation: 37 779

2

MATL, 11 bytes

&:ts2^w2^s-

Try it online!

Explanation:

&:           #Create a range from the input
  t          #Duplicate it
   s2^       #Sum it and square it
      w      #swap the two ranges
       2^s   #Square it and sum it
          -  #Take the difference

James

Posted 2016-06-20T13:53:40.917

Reputation: 54 537

2

Pyth, 11 bytes

s*M-F#^}FQ2

Try it online!

s*M-F#^}FQ2
       }FQ    Compute the range
      ^   2   Generate all pairs
   -F#        Remove those pairs who have identical elements
 *M           Product of all pairs
s             Sum.

Leaky Nun

Posted 2016-06-20T13:53:40.917

Reputation: 45 011

Nice usage of filter. Though there is already a build-in for this task: s*M.P}FQ2 – Jakube – 2016-06-20T21:30:20.990

1

Whispers v2, 90 bytes

> Input
> Input
> 2
>> 1…2
>> L*3
>> Each 5 4
>> ∑6
>> ∑4
>> 8*3
>> 9-7
>> Output 10

Try it online!

caird coinheringaahing

Posted 2016-06-20T13:53:40.917

Reputation: 13 702

1

Julia 0.6, 21 bytes

r->sum(r)^2-sum(r.^2)

Returns an anonymous function that takes a Range, eg f(1:10), which then returns the result.

Try it online!

gggg

Posted 2016-06-20T13:53:40.917

Reputation: 1 715

1

C (gcc), 67 bytes

f(n,m){double a,b;for(;n<=m;a+=n,b+=pow(n++,2));return pow(a,2)-b;}

Try it online!

SIGSTACKFAULT

Posted 2016-06-20T13:53:40.917

Reputation: 585

1

Jelly, 6 bytes

rµÄḋḊḤ

Recent improvements to the Jelly language allow a compact implementation of the \$g\$ function from my Python answer.

Try it online!

How it works

rµÄḋḊḤ  Main link. Arguments: a, b (integers)


r       Range; yield R := [a, ..., b].
 µ      Begin a monadic chain with argument R.
  Ä     Accumulate; take the cumulative sum of R.
    Ḋ   Deque; yield [a+1, ..., b].
   ḋ    Take the dot product, ignoring the last term of the cumulative sum.
     Ḥ  Unhalve; double the result.

Dennis

Posted 2016-06-20T13:53:40.917

Reputation: 196 637

1

C (gcc), 48 bytes

a,b;f(n,m){for(a=b=0;m/n;a+=n++)b+=n*n;n=a*a-b;}

Try it online!

ceilingcat

Posted 2016-06-20T13:53:40.917

Reputation: 5 503

1

Red, 70 bytes

func[a b][s: t: 0 until[s: s + a t: a * a + t  b < a: a + 1]s * s - t]

Try it online!

Galen Ivanov

Posted 2016-06-20T13:53:40.917

Reputation: 13 815

1

Excel, 60 bytes

=(B1^2+B1-A1^2+A1)^2/4-(2*B1^3+3*B1^2+B1-2*A1^3+3*A1^2-A1)/6

Algebraic reshuffling of more verbose implementation: For inputs a and b:

(B1*(B1+1)-A1*(A1-1))/2          // (Sum of b) - (Sum of a-1)
(  )^2                           //  squared
B1*(B1+1)*(2*B1+1)/6             //  Sum of (b squared)
A1*(A1-1)*(2*A1-1)/6             //  Sum of (a-1 squared)

Wernisch

Posted 2016-06-20T13:53:40.917

Reputation: 2 534

1

C# (.NET Core), 62 bytes

(a,b)=>{int x=0,y=0;for(;a<=b;a++){x+=a;y+=a*a;}return x*x-y;}

Try it online!

Ungolfed:

(a, b) => {                 // takes in two integer inputs, delimited by a comma
    int x = 0, y = 0;       // initializes x and y
    for(; a <= b; a++)      // increment a until a equals b
    {
        x += a;             // add current a to x
        y += a * a;         // add square of current a to y
    }
    return (x * x) - y;     // return the difference of the square of the sums (x*x) and the sum of the squares (y)
}

Meerkat

Posted 2016-06-20T13:53:40.917

Reputation: 371

1

Python 3, 66 65 bytes

lambda a,b:sum(x*y*2for x in range(a,b+1)for y in range(x+1,b+1))

Try it online!

with @Dennis formulae and w/o recursion, yet another Python solution (as I cannot comment @leaky-nun solution (not enough reputation)

david

Posted 2016-06-20T13:53:40.917

Reputation: 479

This is code-golf, you should try to make your code as short as possible. At least remove the unnecessary whitespaces. Try merging two for loops into one if possible. – user202729 – 2018-11-05T15:31:04.083

Sorry @user202729, this is actually my first contribution. I've edited using your comment and reformatted contribution using TIO. – david – 2018-11-05T15:52:35.557

Did it for the first and forgot it for the second... thanks @Stephen – david – 2018-11-05T15:57:35.817

1

PHP, 58 bytes

for([,$p,$q]=$argv;$p<=$q;$s+=$p++)$t+=$p*$p;echo$s*$s-$t;

Run with -nr or try it online.

Titus

Posted 2016-06-20T13:53:40.917

Reputation: 13 814

1

Sidef, 46 44 bytes

Translation of: my Factor solution

{|a,b|R=a..b;R.map{.sqr}.sum-R.sum.sqr->abs}

Try it online!

use it like x.run(4, 20) -> 38760

Previous

->(a,b,R=a..b){R.map{.sqr}.sum-R.sum.sqr->abs}

longer, explained

->                       # the next list is a function parameter list
(a, b, R = a .. b )      # R is a RangeNum over the a and b 
{                        # a Block
  return                 # return the whole expression
  R.map{ |n|             # map this Block over the range
    return n.sqr         # squared value
  }.sum                  # summed the range
  -                      # subtract
  R.sum.sqr              # sum of the range, squared
  ->abs                  # call Number.abs on everything on the left-hand side of ->
}                        # ok, we're done 

cat

Posted 2016-06-20T13:53:40.917

Reputation: 4 989

1

Tcl, 76 80 bytes

proc S l\ u {while \$l<=$u {incr Q $l
append R -$l*$l
incr l}
expr $Q**2+$R}

Try it online!

sergiol

Posted 2016-06-20T13:53:40.917

Reputation: 3 055

1

Burlesque - 16 bytes

r@J++2?^j)S[++?-

r@                  range
  J                 dup
   ++               sum
     2?^            square it
        j           swap
         )S[        map (square)
            ++      sum
              ?-    subtract

Alternate versions:

r@JJ?*++j++S[?-ab
r@J++2?^jqS[ms?-
r@J++J?*jqS[ms?-
r@J++J?*jJ?*++?-
r@J)S[++j++S[j?-

^- and this is the art of golfing :(.

mroman

Posted 2016-06-20T13:53:40.917

Reputation: 1 382

1

Rust, 67 bytes

|b,e|{let mut t=0;let mut s=0;for i in b..=e{t+=i;s+=i*i;}(t*t)-s};

A closure that takes two integers and returns an integer.

T_human

Posted 2016-06-20T13:53:40.917

Reputation: 31

1

Pony, 73 bytes

fun f(m:U64,n:U64,s:U64=0):U64=>if m>n then 0 else(2*m*s)+f(m+1,n,m+s)end

sort of ungolfed

  fun apply(m: U64, n: U64, s: U64 = 0): U64 =>
    if m > n then 0
    else (2 * m * s) + apply(m + 1, n, m + s) end

Port of Neil's JavaScript solution.

cat

Posted 2016-06-20T13:53:40.917

Reputation: 4 989

1

Aheui (esotope), 108 bytes(36 chars)

방빠방빠쌍다쌍상싸사타빠밤타빠받다파반다받상싸사빠따따다따따받밤따나망히

Try it online!


Takes two inputs from user(separated by line feed or whitespace) and print result of following function;

\$f(a,b)=((a-b)\cdot(a-b-1)\cdot(3\cdot(a+b)^2+a-b-2))/12\$

cobaltp

Posted 2016-06-20T13:53:40.917

Reputation: 401

1

CJam, 17 bytes

q~),>_:+2#\2f#:+-

Test it here.

Explanation

q~       e# Read and evaluate input, dumping M and N on the stack.
),       e# Increment, create range [0 1 ... N].
>        e# Discard first M elements, yielding [M M+1 ... N].
_        e# Duplicate.
:+2#     e# Sum and square.
\2f#:+   e# Swap with other copy. Square and sum.
-        e# Subtract.

Alternatively, one can just sum the products of all distinct pairs (basically multiplying out the square of the sum, and removing squares), but that's a byte longer:

q~),>2m*{)-},::*:+

Martin Ender

Posted 2016-06-20T13:53:40.917

Reputation: 184 808

1

PowerShell v2+, 47 bytes

Two variations

param($n,$m)$n..$m|%{$o+=$_;$p+=$_*$_};$o*$o-$p

$args-join'..'|iex|%{$o+=$_;$p+=$_*$_};$o*$o-$p

In both cases we're generating a range with the .. operator, piping that to a loop |%{...}. Each iteration, we're accumulating $o and $p as either the sum or the sum-of-squares. We then calculate the square-of-sums with $o*$o and subtract $p. Output is left on the pipeline and printing is implicit.

AdmBorkBork

Posted 2016-06-20T13:53:40.917

Reputation: 41 581

1

JavaScript (ES6), 67 bytes

a=>b=>([s=q=0,...Array(b-a)].map((_,i)=>q+=(s+=(n=i+a),n*n)),s*s-q)

Test Suite

f=a=>b=>([s=q=0,...Array(b-a)].map((_,i)=>q+=(s+=(n=i+a),n*n)),s*s-q)
e=s=>`${s} => ${eval(s[0])}` // template tag format for tests
console.log(e`f(5)(9)`)
console.log(e`f(91)(123)`)
console.log(e`f(1)(10)`)

Patrick Roberts

Posted 2016-06-20T13:53:40.917

Reputation: 2 475

1

J, 29 bytes

Port of Doorknob's Jelly answer.

[:(+/@(^&2)-~2^~+/)[}.[:i.1+]

Usage

>> f = [:(+/@(^&2)-~2^~+/)[}.[:i.1+]
>> 91 f 123x
<< 12087152

Where >> is STDIN, << is STDOUT, and x is for extended precision.

Leaky Nun

Posted 2016-06-20T13:53:40.917

Reputation: 45 011

1

Pyke, 11 bytes

h1:Ds]MXXs-

Try it here!

h1:         - inclusive_range(input)
   Ds]      -     [^, sum(^)]
      MX    -    deep_map(^, <--**2)
         s  -   ^[1] = sum(^[1])
          - -  ^[0]-^[1]

Blue

Posted 2016-06-20T13:53:40.917

Reputation: 26 661

1

Julia, 25 bytes

f(a,b,x=a:b)=sum(x)^2-x'x

This is a function that accepts two integers and returns a 1x1 integer array.

The approach is simple: Construct a UnitRange from the endpoints a and b and call it x, then sum x, square it, and subtract its norm, which is computed as transpose(x) * x.

Try it online! (includes all test cases)

Alex A.

Posted 2016-06-20T13:53:40.917

Reputation: 23 761

1a\b=-(x=a:b)'x+sum(x)^2 saves a few bytes. – Dennis – 2016-06-20T21:54:22.223

1

TI-BASIC, 19 bytes

Prompt N,M
randIntNoRep(N,M
sum(Ans)2-sum(Ans2

randIntNoRep gets the range (shuffled). The rest is pretty self explanatory.

Conor O'Brien

Posted 2016-06-20T13:53:40.917

Reputation: 36 228

1

Fith, 52 bytes

{ 1 + range dup sum 2 pow swap { 2 pow } map sum - }

This is an anonymous function that takes the two numbers on the stack and leaves a single number.

Explanation:

{
    1 + range dup      2 ranges from a to b inclusive
    sum 2 pow          Sum one and square it
    swap               Bring a fresh range to the top
    { 2 pow } map sum  Square every element and sum the list
    -                  Subtract
}

jqblz

Posted 2016-06-20T13:53:40.917

Reputation: 2 062

1

If you like postfix, point-free and stack-based functional prorgamming you might like Factor :D

– cat – 2016-06-23T13:50:56.553

1

GeoGebra, 91 bytes

a(x)=(x²+x)/2
b(x)=x³/3+x²/2+x/6
c(x,y)=(a(y)-a(x))²
d(x,y)=b(y)-b(x)
c(x-1,y)-d(x-1,y)

Defines a function (probably e(x,y)) that computes the desired difference.
a(x) calculates the sum of natural numbers between 0 and x.
b(x) calculates the sum of the squares of the natural numbers between 0 and x.
c(x,y) first computes the sum of the natural numbers between x and y, then squares that sum.
d(x,y) calculates the sum of squares between b(x) and b(y).
The last line defines a multi-variable function that finishes the calculation. The function is automatically assigned a name, saving a few bytes.

Joe

Posted 2016-06-20T13:53:40.917

Reputation: 895

Hi, how do I call the function that this defines? I was able to figure out the input at https://www.geogebra.org/classic#cas , but couldn't figure out how to find or call the final function.

– sundar - Reinstate Monica – 2018-07-02T06:27:52.640

@sundar: The last line is an expression in x and y. We could prepend e(x,y)= to give it a name, but to save bytes, we don’t here. GeoGebra automatically assigns the expression a name (probably e, since that’s the next available letter). I don’t have the environment available right now, but I wouldn’t use the CAS pane. The algebra pane and input bar should do the job right. (It’s been a while since I used GGb online; my mental image of it may be outdated.) – Joe – 2018-07-13T04:54:06.800

1

R - 33 bytes

x=scan():scan();sum(x)^2-sum(x^2)

pass your lower limit to the first scan then your upper limit to the second scan

bouncyball

Posted 2016-06-20T13:53:40.917

Reputation: 401

0

Python 2.7, 82 bytes 85 bytes

def a(l, u):
    c=0
    d=0
    for e in range(l, u+1):
        c+=e
        d+=e**2
    return c**2-d

Works in base 10.

StealthyPanda

Posted 2016-06-20T13:53:40.917

Reputation: 41

1

Currently your answer is invalid (use the test cases to verify it): 1. You forgot to square c 2. You have to subtract the sum of squares from the square of the sum, so c**2-d 3. I suggest to golf your code, and you can count newlines as one byte instead of two 4. I suggest adding a Try it online! link

– wastl – 2018-07-09T19:32:35.840

0

Julia 0.6, 21 bytes

r->2triu(r*r',1)|>sum

Try it online!

Julia port of Luis Mendo's MATL answer. Comes out to the same bytecount as the other Julia answer by @gggg. Takes a Range similar to that answer, does a matrix multiply of it with its transpose to get all pairwise products in a matrix. Takes the upper triangular portion of that (the 1 argument is to denote the distance from the leading diagonal to start from), multiplies that by 2, and finally sums the values and returns that implicitly.

sundar - Reinstate Monica

Posted 2016-06-20T13:53:40.917

Reputation: 5 296

0

Wolfram Language (Mathematica), 18 bytes

Tr@#^2-#.#&@*Range

Try it online!

Composition of Tr@#^2-#.#& (square of sum minus sum of squares, where sum of squares is implemented via dot product) and Range (list of all integers between the two inputs). If you like seeing the operations in order, Range/*Tr@#^2-#.#& is equivalent.

As a bonus, also solves this challenge with no modifications, since Range can either take one argument (giving the range from 1 to the input) or two. (But it's not the most efficient solution possible there.)

Misha Lavrov

Posted 2016-06-20T13:53:40.917

Reputation: 4 846

0

Bash, 74 65 bytes

x=y=0;for i in `seq $1 $2`;{ x=$[x+i];y=$[y+i*i]; };echo $[x*x-y]

Try it online!

I'm no expert at bash golfing, but this works.
Managed to cut 9 bytes just by reading through the bash golfing tips thread

Skidsdev

Posted 2016-06-20T13:53:40.917

Reputation: 9 656

for((i=$1;i<=$2;x+=i,y+=i*i++)){ :;};echo $[x*x-y] saves 15 bytes. – Dennis – 2018-11-23T01:37:20.213

0

Tcl, 105 bytes

proc d a\ b {while {[incr a]<=$b} {set j $a
while \$j<=$b {incr p [expr 2*([incr j]-1)*($a-1)]}}
expr $p}

Try it online!

# Tcl, 112 bytes

proc d a\ b {set i [expr $a-1]
while \$i<$b {set j [incr i]
while \$j<$b {incr p [expr 2*[incr j]*$i]}}
expr $p}

david

Posted 2016-06-20T13:53:40.917

Reputation: 479

0

Python, 62 bytes

lambda a,b:sum(range(a,b+1))**2-sum(x*x for x in range(a,b+1))

Or, longer:

lambda a,b:sum(sum(x*y for y in range(a,b+1)if x-y)for x in range(a,b+1))

Ideone both!

Leaky Nun

Posted 2016-06-20T13:53:40.917

Reputation: 45 011

This seems to be 63 bytes? (Did you forget the lambda a,b:?) Anyway, it seems like the naive: lambda a,b:sum(range(a,b+1))**2-sum(x*x for x in range(a,b+1)) is a byte shorter, unfortunately. – FryAmTheEggman – 2016-06-20T14:16:34.463

1I'm not quite sure this works, just ran it against the test and 5,9 yields 995? – george – 2016-06-20T14:18:39.133

0

Java, 95 bytes

public int d(int a,int b){int i=a,j,s=0;for(;i<=b;i++)for(j=a;j<=b;j++)s+=i==j?0:i*j;return s;}

Ideone it!

Leaky Nun

Posted 2016-06-20T13:53:40.917

Reputation: 45 011

0

Actually, 11 bytes

u@x;♂²Σ@Σ²-

Try it online!

Leaky Nun

Posted 2016-06-20T13:53:40.917

Reputation: 45 011

0

R, 23 bytes

sum(i:j)^2-sum((i:j)^2)

Does pretty much what you expect by taking i and j as inputs.

Forgottenscience

Posted 2016-06-20T13:53:40.917

Reputation: 417

you can save a byte by assigning the range to a variable in the first sum. sum(a<-i:j)^2-sum(a^2) – MickyT – 2016-06-20T19:05:15.120

2This assumes that the variables i and j are already defined, which makes this a snippet. By default we require all submissions to be either full programs which take input from STDIN and print output to STDOUT, or functions that accept arguments and return values. You can fix this by prepending function(i,j) to the beginning. – Alex A. – 2016-06-20T19:46:39.873

1In fact, all of your answers on the site thus far appear to be snippets. Please adjust them to be programs or functions accordingly. – Alex A. – 2016-06-20T19:48:00.873

0

Actually, 10 bytes

u@x;;*@Σ²-

Try it online!

Explanation:

u@x;;*@Σ²-
u@x         range(a, b+1)
   ;;       two copies
     *      dot product with itself (equal to sum of squares)
      @Σ²   sum remaining copy, square sum
         -  subtract

Mego

Posted 2016-06-20T13:53:40.917

Reputation: 32 998

0

Perl 5.10, 41 bytes

map{$s+=$_,$r+=$_**2}(<>..<>);say$s**2-$r

Input is given on 2 lines, for instance:

61
127

Try it here!

Paul Picard

Posted 2016-06-20T13:53:40.917

Reputation: 863

0

CoffeeScript, 49 Bytes

f=(n,m,s=0)->if n>m then 0else 2*n*s+f(n+1,m,n+s)

Translation of Neil's answer

Output:

f 91, 123 == 12087152 => true

emiflake

Posted 2016-06-20T13:53:40.917

Reputation: 131