# How can I compute the sum of all i² for i between n and m?

How can I write a script to sum the squares of integers between two values `n` and `m`, meaning the sum of all `i`², where `i` runs from `n` to `m`?

• Have you tried anything? Sounds like you'll just need a loop and some arithmetic expansion. – Eric Renouf Sep 15 '16 at 17:12

## 3 Answers

One way to do it:

``````#! /bin/sh
n=\$1
m=\$2
# Reference: http://math.stackexchange.com/q/48080
sum=\$(( (m * (m + 1) * (2 * m + 1) - (n - 1) * n * (2 * n - 1)) / 6 ))
echo \$sum
``````

Result:

``````./sum 3 7
135
``````

A rather basic approach:

``````#!/bin/bash
sum=0                      # initialise sum to zero
for i in \$(seq \$1 \$2); do  # iterate from n to m
sum=\$((sum + i * i))   # add i² to sum
done
echo \$sum                  # print sum
``````

Call:

``````./sum.sh n m
``````

There are other ways to write the loop though, have a look here.

Using Haskell, we can:

``````ghc -e 'sum [i*i | i <- [3..7]]'
``````

or in bash script format:

``````#!/bin/bash
ghc -e "sum [i*i | i <- [\$1..\$2]]"
``````