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\$ Jun 20, 2016 at 14:08
  • \$\begingroup\$ @BradGilbertb2gills edited for clarity \$\endgroup\$
    – george
    Jun 20, 2016 at 14:20
  • \$\begingroup\$ This is simpler than it looks ? \$\endgroup\$
    – cat
    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
    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
    Jun 22, 2016 at 21:17

68 Answers 68

1
\$\begingroup\$

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)

\$\endgroup\$
1
  • 1
    \$\begingroup\$ a\b=-(x=a:b)'x+sum(x)^2 saves a few bytes. \$\endgroup\$
    – Dennis
    Jun 20, 2016 at 21:54
1
\$\begingroup\$

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.

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

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
}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ If you like postfix, point-free and stack-based functional prorgamming you might like Factor :D \$\endgroup\$
    – cat
    Jun 23, 2016 at 13:50
1
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ Hi, how do I call the function that this defines? I was able to figure out the input at geogebra.org/classic#cas , but couldn't figure out how to find or call the final function. \$\endgroup\$
    – Sundar R
    Jul 2, 2018 at 6:27
  • \$\begingroup\$ @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.) \$\endgroup\$
    – juh
    Jul 13, 2018 at 4:54
1
\$\begingroup\$

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

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

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!

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

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!

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

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!

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

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!

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

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!

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

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

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)
}
\$\endgroup\$
1
\$\begingroup\$

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.

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

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)

\$\endgroup\$
3
  • \$\begingroup\$ 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. \$\endgroup\$
    – DELETE_ME
    Nov 5, 2018 at 15:31
  • \$\begingroup\$ Sorry @user202729, this is actually my first contribution. I've edited using your comment and reformatted contribution using TIO. \$\endgroup\$
    – david
    Nov 5, 2018 at 15:52
  • \$\begingroup\$ Did it for the first and forgot it for the second... thanks @Stephen \$\endgroup\$
    – david
    Nov 5, 2018 at 15:57
1
\$\begingroup\$

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

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

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

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.

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

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!

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

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.

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

K (oK), 24 bytes

{(t*t:+/s)-+/s*s:x_!1+y}

Try it online!

"Boring" but straightforward.

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

JavaScript, 49 bytes

Without recursion:

(b,e)=>eval('for(x=y=0;b<=e;y+=b*b++)x+=b;x*x-y')

Try it:

f=(b,e)=>eval('for(x=y=0;b<=e;y+=b*b++)x+=b;x*x-y')

console.log(f(5,9)); // 970
console.log(f(91,123)); // 12087152
console.log(f(1,10)); // 2640

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

Pyt, 8 bytes

ŘĐĐƩ²↔·-

Try it online!

Takes two inputs on separate lines as max, min

Ř               implicit inputs; Řange
 ĐĐ             Đuplicate array on stack twice
   Ʃ²           Get square of sum
     ⇹·         Get sum of squares
       -        Subtract; implicit print
\$\endgroup\$
1
\$\begingroup\$

Ly, 22 bytes

nnR&s&+:*>l[:*sp<l->]<

Try it online!

This is a straight forward interpretation of the rules...

nnR                     - get the start/end, generate the sequence of numbers
   &s                   - save the sequence...
     &+                 - sum it
       :*               - square the sum
         >l             - load the sequence on a new stack
           [        ]   - while the stack isn't empty
            :*          - square the number
              sp<l      - move the squared number to the other stack
                  ->    - subtract and go back to the second stack
                     <  - switch back to the accumulator stack
                        - the number on the stack prints automatically on exit
\$\endgroup\$
1
\$\begingroup\$

Arturo, 42 35 bytes

$=>[-*<=∑r∑map r:<=&..&'z->z*z]

Try it

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

J-uby, 33 bytes

:!~|:-%[:sum|g= ~:**&2,:*&g|:sum]

(The space between = and ~ is necessary to keep the Ruby lexer from interpreting them as the =~ operator.)

Explanation

:!~ | :- % [:sum | g = ~:** & 2, :* & g | :sum]

:!~ |                                            # Range, then
      :- % [                   ,              ]  # difference of...
            :sum | g = ~:** & 2                  #   sum, then square (save the square function in g), and
                                 :* & g | :sum   #   map with square, then sum

Attempt This Online!

\$\endgroup\$
0
\$\begingroup\$

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!

\$\endgroup\$
0
\$\begingroup\$

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!

\$\endgroup\$
2
  • \$\begingroup\$ 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. \$\endgroup\$ Jun 20, 2016 at 14:16
  • 1
    \$\begingroup\$ I'm not quite sure this works, just ran it against the test and 5,9 yields 995? \$\endgroup\$
    – george
    Jun 20, 2016 at 14:18
0
\$\begingroup\$

Actually, 11 bytes

u@x;♂²Σ@Σ²-

Try it online!

\$\endgroup\$
0
\$\begingroup\$

R, 23 bytes

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

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

\$\endgroup\$
3
  • \$\begingroup\$ you can save a byte by assigning the range to a variable in the first sum. sum(a<-i:j)^2-sum(a^2) \$\endgroup\$
    – MickyT
    Jun 20, 2016 at 19:05
  • 2
    \$\begingroup\$ This 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. \$\endgroup\$
    – Alex A.
    Jun 20, 2016 at 19:46
  • 1
    \$\begingroup\$ In fact, all of your answers on the site thus far appear to be snippets. Please adjust them to be programs or functions accordingly. \$\endgroup\$
    – Alex A.
    Jun 20, 2016 at 19:48
0
\$\begingroup\$

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