-2

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?

  • 3
    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

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
1

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.

1

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]]"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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