42
\$\begingroup\$

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.

\$\endgroup\$
8
  • 12
    \$\begingroup\$ It took me a while to realize the input was the endpoints of a range. \$\endgroup\$ Commented Jun 20, 2016 at 14:08
  • \$\begingroup\$ @BradGilbertb2gills edited for clarity \$\endgroup\$
    – george
    Commented Jun 20, 2016 at 14:20
  • \$\begingroup\$ This is simpler than it looks ? \$\endgroup\$
    – cat
    Commented Jun 22, 2016 at 20:17
  • \$\begingroup\$ @cat what do you mean by that? Yes the maths is simple Alevel stuff. But it's all down to how you golf it \$\endgroup\$
    – george
    Commented Jun 22, 2016 at 20:18
  • \$\begingroup\$ @george The question and many of the answers make it look like a lot of work, but it's not \$\endgroup\$
    – cat
    Commented Jun 22, 2016 at 21:17

68 Answers 68

24
\$\begingroup\$

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

$$ \newcommand{\sumab}[2]{\sum_{a \le #1 \le b} #2 \:} \begin{align} g(a,b) & = \left( \sumab n n \right)^2 - \sumab n {n^2} \\ & = \sumab {i,j} {ij} - \sumab n {n^2} \\ & = \sumab {i<j} {ij} + \sumab {i=j} {ij} + \sumab {j<i} {ij} - \sumab n {n^2} \\ & = 2 \sumab {j<i} {ij} \\ & = 2 \sumab {i} {\sum_{a \le i < j} ij} \\ & = \sumab {i} {\left( 2i \sum_{a \le j < i} j \right)} \end{align} $$

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

$$ f(x, y, s) = \begin{cases} 2xs + f(x+1, y, s+x) & \text{ if } x \le y \\ 0 & \text{ if} x > y \end{cases} $$

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

$$ \begin{align} f(a, b, 0) & = 2\cdot0 + f(a+1, b, a) \\ & = 2\cdot0 + 2\cdot(a+1)\cdot a + f(a+2, b, a+(a+1)) \\ & = 2\cdot0 + 2\cdot(a+1)\cdot a + 2\cdot(a+2)\cdot(a+(a+1)) + f(a+3, b, a+(a+1)+(a+2)) \\ & \vdots \\ & = \sumab {i} {\left( 2i \sum_{a \le j < i} j \right)} + f\left(b+1, b, \sumab j j\right) \\ & = \sumab {i} {\left( 2i \sum_{a \le j < i} j \right)} \\ & = g(a, b) \end{align} $$

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.

\$\endgroup\$
5
  • \$\begingroup\$ ah okay. Could you explain your method though? \$\endgroup\$
    – george
    Commented Jun 20, 2016 at 18:33
  • \$\begingroup\$ I will, but I'm currently trying to golf it a bit more. \$\endgroup\$
    – Dennis
    Commented Jun 20, 2016 at 18:34
  • \$\begingroup\$ 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! \$\endgroup\$
    – george
    Commented Jun 20, 2016 at 21:27
  • 2
    \$\begingroup\$ @george I've finished the explanation. \$\endgroup\$
    – Dennis
    Commented Jun 20, 2016 at 22:53
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Jun 22, 2016 at 14:11
15
\$\begingroup\$

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
    
\$\endgroup\$
1
  • 8
    \$\begingroup\$ I really like seeing the partial results. They really help with understanding the program. Thanks for including them! \$\endgroup\$
    – DanTheMan
    Commented Jun 20, 2016 at 21:54
10
\$\begingroup\$

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!

\$\endgroup\$
5
  • 3
    \$\begingroup\$ For once, Jelly is actually very readable. \$\endgroup\$
    – Adám
    Commented Jun 20, 2016 at 14:22
  • \$\begingroup\$ Can I fork this to my answer? \$\endgroup\$
    – Leaky Nun
    Commented Jun 20, 2016 at 15:08
  • \$\begingroup\$ @LeakyNun what does that mean? \$\endgroup\$
    – Doorknob
    Commented Jun 20, 2016 at 15:17
  • \$\begingroup\$ This. \$\endgroup\$
    – Leaky Nun
    Commented Jun 20, 2016 at 15:21
  • 7
    \$\begingroup\$ Nice earrings: S²_²S \$\endgroup\$ Commented Jun 20, 2016 at 18:22
10
\$\begingroup\$

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.

\$\endgroup\$
5
  • \$\begingroup\$ 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 \$\endgroup\$
    – george
    Commented Jun 20, 2016 at 15:06
  • 1
    \$\begingroup\$ @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)). \$\endgroup\$ Commented Jun 20, 2016 at 15:11
  • \$\begingroup\$ @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*(2*b+1)-a*~-a*(2*a-1))/6 if that is of any use. I have golfed as much as I can the two formula \$\endgroup\$
    – george
    Commented Jun 20, 2016 at 15:15
  • \$\begingroup\$ @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. \$\endgroup\$
    – Sp3000
    Commented Jun 21, 2016 at 0:16
  • \$\begingroup\$ @Sp3000 that's a great way to do it. I'll try that in future \$\endgroup\$
    – george
    Commented Jun 21, 2016 at 5:17
6
\$\begingroup\$

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

\$\endgroup\$
2
  • \$\begingroup\$ Is 05AB1E a ROT13 version of Jelly maybe? Substitute r by Ÿ, µ by D, S by O, ² by n, _ by s and $ by -. \$\endgroup\$ Commented Jun 20, 2016 at 18:24
  • 4
    \$\begingroup\$ @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. \$\endgroup\$
    – Emigna
    Commented Jun 20, 2016 at 18:29
6
\$\begingroup\$

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].
\$\endgroup\$
4
  • \$\begingroup\$ Would Variance help? \$\endgroup\$
    – Leaky Nun
    Commented Jun 20, 2016 at 14:51
  • \$\begingroup\$ @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. \$\endgroup\$ Commented Jun 20, 2016 at 14:53
  • 1
    \$\begingroup\$ Tr@#^2-#.#&@*Range is only 18 bytes. \$\endgroup\$ Commented Nov 5, 2018 at 15:58
  • \$\begingroup\$ @MishaLavrov neat! Feel free to make it a separate answer. :) \$\endgroup\$ Commented Nov 5, 2018 at 20:51
5
\$\begingroup\$

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.

\$\endgroup\$
4
\$\begingroup\$

Haskell, 34 bytes

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

Usage example: 91 # 123 -> 12087152.

Nothing to explain.

\$\endgroup\$
3
\$\begingroup\$

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
\$\endgroup\$
3
\$\begingroup\$

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)
\$\endgroup\$
0
3
\$\begingroup\$

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.

\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$
7
  • \$\begingroup\$ 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). \$\endgroup\$ Commented Jun 20, 2016 at 18:32
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Jun 20, 2016 at 18:34
  • \$\begingroup\$ Great catch @MartinEnder, thank you :) \$\endgroup\$ Commented Jun 20, 2016 at 18:51
  • \$\begingroup\$ Also based on what Martin had in mind, this seems to be a bit shorter. \$\endgroup\$ Commented Jun 20, 2016 at 18:59
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ Commented Jun 20, 2016 at 19:38
3
\$\begingroup\$

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
\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ Try using n=>m=>eval(`for(s=t=0;n<=m;t+=n++)s+=n*n;t*t-s`) \$\endgroup\$ Commented Jun 21, 2016 at 15:24
  • \$\begingroup\$ @MamaFunRoll On the other hand, I could try porting Dennis♦'s Python solution... \$\endgroup\$
    – Neil
    Commented Jun 22, 2016 at 12:49
3
\$\begingroup\$

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
]
\$\endgroup\$
3
\$\begingroup\$

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

\$\endgroup\$
2
  • 1
    \$\begingroup\$ You don't need the parens around i+1. \$\endgroup\$
    – Wheat Wizard
    Commented Jul 2, 2018 at 2:50
  • 2
    \$\begingroup\$ Also if you want to talk Haskell and Haskell golfing you can join us in the chat room. \$\endgroup\$
    – Wheat Wizard
    Commented Jul 2, 2018 at 2:51
3
\$\begingroup\$

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
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Save a byte moving the assignment and evading parens: {$_=$^a..$^b;.sum²-[+] $_»²} \$\endgroup\$
    – Phil H
    Commented Jul 2, 2018 at 10:39
  • 1
    \$\begingroup\$ 25 bytes: {.sum²-[+] $_»²}o&[..] \$\endgroup\$
    – nwellnhof
    Commented Nov 5, 2018 at 10:29
3
\$\begingroup\$

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\$

\$\endgroup\$
2
\$\begingroup\$

APL, 23 20 bytes

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

Works in NARS2000.

\$\endgroup\$
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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.
\$\endgroup\$
1
  • \$\begingroup\$ Nice usage of filter. Though there is already a build-in for this task: s*M.P}FQ2 \$\endgroup\$
    – Jakube
    Commented Jun 20, 2016 at 21:30
2
\$\begingroup\$

Japt, 10 bytes

õV
x²aUx ²

Try it

\$\endgroup\$
2
\$\begingroup\$

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.
\$\endgroup\$
2
\$\begingroup\$

Vyxal, 8 bytes

ṡ:²∑$∑²ε

Try it Online!

How?

ṡ:²∑$∑²ε
ṡ        # Inclusive range between (implicit) second input and (implicit) first input
 :       # Duplicate this range
  ²      # Square each of the duplicate
   ∑     # Summate
    $    # Swap so the other range is at the top
     ∑   # Summate
      ²  # Then square
       ε # Absolute difference between the two
\$\endgroup\$
2
\$\begingroup\$

Thunno 2, 8 bytes

IDS²s²S-

Attempt This Online!

Explanation

IDS²s²S-  # Implicit input
ID        # Inclusive range; duplicate
  S²      # Sum the list; square the sum
    s     # Swap so the range is back on top
     ²S   # Square each item; sum the list
       -  # Take the difference
          # Implicit output
\$\endgroup\$
1
\$\begingroup\$

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*{)-},::*:+
\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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]
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.