Task

The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n.

Show output for n = 1000.

This is is the same as Project Euler problem 1.

Extra credit: do this efficiently for n = 1e20 or higher.




function sum_multiples {
  typeset -i n=$1 limit=$2
  typeset -i max=limit-1
  (( max -= max % n ))
  printf '%d\n' $(( max / n * (n+max)/2 ))
}
 
function sum35 {
  typeset -i limit=$1
  printf '%d\n' $((  $(sum_multiples  3 $limit)
                   + $(sum_multiples  5 $limit)
                   - $(sum_multiples 15 $limit) ))
}
 
for (( l=1; l<=1000000000; l*=10 )); do
  printf '%10d\t%18d\n' "$l" "$(sum35 "$l")"
done