Sum of squares

From Rosetta Code
Revision as of 19:32, 18 January 2011 by Sonia (talk | contribs) (Go solution)
Task
Sum of squares
You are encouraged to solve this task according to the task description, using any language you may know.

Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of 0).

See also Mean.

ActionScript

<lang ActionScript>function sumOfSquares(vector:Vector.<Number>):Number { var sum:Number = 0; for(var i:uint = 0; i < vector.length; i++) sum += vector[i]*vector[i]; return sum; }</lang>

Ada

<lang ada>with Ada.Text_IO; use Ada.Text_IO;

procedure Test_Sum_Of_Squares is

  type Float_Array is array (Integer range <>) of Float;
  function Sum_Of_Squares (X : Float_Array) return Float is
     Sum : Float := 0.0;
  begin
     for I in X'Range loop
        Sum := Sum + X (I) ** 2;
     end loop;
     return Sum;
  end Sum_Of_Squares;
  

begin

  Put_Line (Float'Image (Sum_Of_Squares ((1..0 => 1.0)))); -- Empty array
  Put_Line (Float'Image (Sum_Of_Squares ((3.0, 1.0, 4.0, 1.0, 5.0, 9.0))));

end Test_Sum_Of_Squares;</lang> Sample output:

 0.00000E+00
 1.33000E+02

ALGOL 68

Works with: ALGOL 68 version Revision 1 - no extensions to language used
Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny
Works with: ELLA ALGOL 68 version Any (with appropriate job cards) - tested with release 1.8-8d

The computation can be written as a loop. <lang algol68>PROC sum of squares = ([]REAL argv)REAL:(

 REAL sum := 0;
 FOR i FROM LWB argv TO UPB argv DO
   sum +:= argv[i]**2
 OD;
 sum

); test:(

 printf(($g(0)l$,sum of squares([]REAL(3, 1, 4, 1, 5, 9))));

)</lang> Output:

133

Another implementation could define a procedure (proc) or operator (op) called map.

Translation of: python

<lang algol68>[]REAL data = (3, 1, 4, 1, 5, 9);

PROC map = ( PROC(REAL)REAL func, []REAL argv)REAL:

   ( REAL out:=0; FOR i FROM LWB argv TO UPB argv DO out:=func(argv[i]) OD; out);

test:(

 REAL sum := 0;
 printf(($xg(0)l$, map ( ((REAL argv)REAL: sum +:= argv ** 2), data) ));
 PRIO MAP = 5; # the same priority as the operators <, =<, >=, & > maybe... #
 OP MAP = ( PROC(REAL)REAL func, []REAL argv)REAL:
   ( REAL out:=0; FOR i FROM LWB argv TO UPB argv DO out:=func(argv[i]) OD; out);
 sum := 0;
 printf(($g(0)l$, ((REAL argv)REAL: sum +:= argv ** 2) MAP data ))

)</lang> Output:

133
133

AutoHotkey

<lang autohotkey>list = 3 1 4 1 5 9 Loop, Parse, list, %A_Space%

sum += A_LoopField**2

MsgBox,% sum</lang>

AWK

Vectors are read, space-separated, from stdin; sum of squares goes to stdout. The empty line produces 0. <lang awk>$ awk '{s=0;for(i=1;i<=NF;i++)s+=$i*$i;print s}' 3 1 4 1 5 9 133

0</lang>

BASIC

Works with: QBasic

Assume the numbers are in an array called a. <lang qbasic>sum = 0 FOR I = LBOUND(a) TO UBOUND(a)

 sum = sum + a(I) ^ 2

NEXT I PRINT "The sum of squares is: " + sum</lang>

Brat

<lang brat>p 1.to(10).reduce 0 { res, n | res = res + n ^ 2 } #Prints 385</lang>

C

<lang c>#include <stdio.h>

double squaredsum(double *l, int e) {

  int i; double sum = 0.0;
  for(i = 0 ; i < e ; i++) sum += l[i]*l[i];
  return sum;

}

int main() {

  double list[6] = {3.0, 1.0, 4.0, 1.0, 5.0, 9.0};
  
  printf("%lf\n", squaredsum(list, 6));
  printf("%lf\n", squaredsum(list, 0));
  /* the same without using a real list as if it were 0-element long */
  printf("%lf\n", squaredsum(NULL, 0));
  return 0;

}</lang>

C++

<lang cpp>#include <iostream>

  1. include <numeric>
  2. include <vector>

double add_square(double prev_sum, double new_val) {

 return prev_sum + new_val*new_val;

}

double vec_add_squares(std::vector<double>& v) {

 return std::accumulate(v.begin(), v.end(), 0.0, add_square);

}

int main() {

 // first, show that for empty vectors we indeed get 0
 std::vector<double> v; // empty
 std::cout << vec_add_squares(v) << std::endl;
 // now, use some values
 double data[] = { 0, 1, 3, 1.5, 42, 0.1, -4 };
 v.assign(data, data+7);
 std::cout << vec_add_squares(v) << std::endl;
 return 0;

}</lang>

Alternative version using

Library: Boost.Lambda

:

<lang cpp>#include <numeric>

  1. include <vector>
  2. include "boost/lambda/lambda.hpp"

double vec_add_squares(std::vector<double>& v) {

 using namespace boost::lambda;
 return std::accumulate(v.begin(), v.end(), 0.0, _1 + _2 * _2);

}</lang>

C#

<lang csharp>using System; using System.Collections.Generic; using System.Linq;

class Program {

   static int sumsq(ICollection<int> i) {
       if (i == null || i.Count == 0) return 0;
       return i.Select(x => x * x).Sum();
   }
   static void Main() {
       int[] a = { 1, 2, 3, 4, 5 };
       Console.WriteLine(sumsq(a)); // 55
   }

}</lang>

Chef

<lang Chef>Sum of squares.

First input is length of vector, then rest of input is vector.

Ingredients. 1 g eggs 0 g bacon

Method. Put bacon into the 1st mixing bowl. Take eggs from refrigerator. Square the eggs. Take bacon from refrigerator. Put bacon into 2nd mixing bowl. Combine bacon into 2nd mixing bowl. Fold bacon into 2nd mixing bowl. Add the bacon into the 1st mixing bowl. Ask the eggs until squared. Pour contents of the 1st mixing bowl into the 1st baking dish.

Serves 1.

</lang>

Clojure

<lang clojure>(defn sum-of-squares [v]

 (reduce #(+ %1 (* %2 %2)) 0 v))</lang>

Common Lisp

<lang lisp>(defun sum-of-squares (vector)

 (loop for x across vector sum (expt x 2)))</lang>

D

<lang d>module sumsquare ; import std.stdio ;

T sumsq(T)(T[] a) {

 T sum = 0 ;
 foreach(e ; a)
   sum += e*e ;
 return sum ;

}

void main() {

 real[] arr = [3.1L,1,4,1,5,9] ; 
 writefln(arr) ;
 writefln(arr.sumsq()) ; 

}</lang> Functional style

Works with: D version 2.011

See std.algorithm <lang d>import std.algorithm ; T sumsq(T)(inout T[] a) {

 return reduce!("a+b")(cast(T)0, map!("a*a")(a)) ;

}</lang>

E

<lang e>def sumOfSquares(numbers) {

   var sum := 0
   for x in numbers {
       sum += x**2
   }
   return sum

}</lang>

Erlang

<lang erlang>lists:foldl(fun(X, Sum) -> X*X + Sum end, 0, [3,1,4,1,5,9]).</lang>

Factor

<lang factor>USE: math sequences ;

sum-of-squares ( seq -- n ) [ sq ] map-sum ;

{ 1.0 2.0 4.0 8.0 16.0 } sum-of-squares</lang>

Forth

<lang forth>: fsum**2 ( addr n -- f )

 0e
 dup 0= if 2drop exit then
 floats bounds do
   i f@ fdup f* f+
 1 floats +loop ;

create test 3e f, 1e f, 4e f, 1e f, 5e f, 9e f, test 6 fsum**2 f. \ 133.</lang>

Fortran

In ISO Fortran 90 orlater, use SUM intrinsic and implicit element-wise array arithmetic: <lang fortran>real, dimension(1000) :: a = (/ (i, i=1, 1000) /) real, pointer, dimension(:) :: p => a(2:1)  ! pointer to zero-length array real :: result, zresult

result = sum(a*a)  ! Multiply array by itself to get squares

result = sum(a**2)  ! Use exponentiation operator to get squares

zresult = sum(p*p)  ! P is zero-length; P*P is valid zero-length array expression; SUM(P*P) == 0.0 as expected</lang>

F#

<lang fsharp>[1 .. 10] |> List.fold (fun a x -> a + x * x) 0 [|1 .. 10|] |> Array.fold (fun a x -> a + x * x) 0</lang>

Go

<lang go> package main

import "fmt"

func main() {

   var sum float
   for _, x := range []float{1,2,.5} {
       sum += x*x
   }
   fmt.Println(sum)

} </lang>

Golfscript

<lang golfscript>{0\{.*+}%}:sqsum;

  1. usage example

[1 2 3]sqsum puts</lang>

Groovy

<lang groovy>def array = 1..3

// square via multiplication def sumSq = array.collect { it * it }.sum() println sumSq

// square via exponentiation sumSq = array.collect { it ** 2 }.sum()

println sumSq</lang>

Output:

14
14

Haskell

<lang haskell>sumOfSquares = sum . map (^ 2)

> sumOfSquares [3,1,4,1,5,9] 133</lang>

IDL

<lang idl>print,total(array^2)</lang>

Icon and Unicon

Icon

<lang icon>procedure main()

  local lst
  lst := []
  #Construct a simple list and pass it to getsum
  every put(lst,seq()\2)
  write(getsum(lst))

end

procedure getsum(lst)

  local total
  total := 0
  every total +:= !lst ^ 2
  return total

end</lang>

Unicon

This Icon solution works in Unicon.

Inform 7

<lang inform7>Sum Of Squares is a room.

To decide which number is the sum of (N - number) and (M - number) (this is summing): decide on N + M.

To decide which number is (N - number) squared (this is squaring): decide on N * N.

To decide which number is the sum of squares of (L - list of numbers): decide on the summing reduction of squaring applied to L.

When play begins: say the sum of squares of {}; say line break; say the sum of squares of {1, 2, 3}; end the story.</lang>

Io

<lang io>list(3,1,4,1,5,9) map(squared) sum</lang>

J

<lang j>ss=: +/ @: *:</lang>

That is, sum composed with square. The verb also works on higher-ranked arrays. For example:

<lang j> ss 3 1 4 1 5 9 133

  ss $0           NB. $0 is a zero-length vector

0

  x=: 20 4 ?@$ 0  NB. a 20-by-4 table of random (0,1) numbers
  ss x

9.09516 5.19512 5.84173 6.6916</lang>

The computation can also be written as a loop. It is shown here for comparison only and is highly non-preferred compared to the version above.

<lang j>ss1=: 3 : 0

z=. 0
for_i. i.#y do. z=. z+*:i{y end.

)

  ss1 3 1 4 1 5 9

133

  ss1 $0

0

  ss1 x

9.09516 5.19512 5.84173 6.6916</lang>

Java

Assume the numbers are in a double array called "nums".

<lang java>... double sum = 0; for(double a : nums){

 sum+= a * a;

} System.out.println("The sum of the squares is: " + sum); ...</lang>

JavaScript

<lang javascript>function sumsq(array) {

   var sum = 0,
       i;
   for(i = 0; i < array.length; i += 1) {
       sum += array[i] * array[i];
   }
   return sum;

}

alert( sumsq( [1,2,3,4,5] ) ); // 55</lang>

Library: Functional

<lang javascript>Functional.reduce("x+y*y", 0, [1,2,3,4,5]) // 55</lang>

Liberty BASIC

<lang lb>' [RC] Sum of Squares

   SourceList$     ="3 1 4 1 5 9"
   'SourceList$     =""
   '   If saved as an array we'd have to have a flag for last data.
   '   LB has the very useful word$() to read from delimited strings.
   '   The default delimiter is a space character, " ".
   SumOfSquares    =0
   n               =0
   data$           ="666"  '   temporary dummy to enter the loop.
   while data$ <>""                                '   we loop until no data left.
       data$           =word$( SourceList$, n +1)  '   first data, as a string
       NewVal          =val( data$)                '   convert string to number
       SumOfSquares    =SumOfSquares +NewVal^2     '   add to existing sum of squares
       n =n +1                                     '   increment number of data items found
   wend
   n =n -1
   print "Supplied data was ";         SourceList$
   print "This contained ";            n; " numbers."
   print "Sum of squares is ";         SumOfSquares
   end</lang>

<lang logo>print apply "sum map [? * ?] [1 2 3 4 5]  ; 55</lang>

Logtalk

<lang logtalk>sum(List, Sum) :-

   sum(List, 0, Sum).

sum([], Sum, Sum). sum([X| Xs], Acc, Sum) :-

   Acc2 is Acc + X,
   sum(Xs, Acc2, Sum).</lang>

Lua

<lang lua>function squaresum(a, ...) return a and a^2 + squaresum(...) or 0 end function squaresumt(t) return squaresum(unpack(t)) end

print(squaresumt{3, 5, 4, 1, 7})</lang>

Mathematica

As a function 1: <lang mathematica>SumOfSquares[x_]:=Total[x^2] SumOfSquares[{1,2,3,4,5}]</lang> As a function 2: <lang mathematica>SumOfSquares[x_]:=x.x SumOfSquares[{1,2,3,4,5}]</lang> Pure function 1: (postfix operator in the following examples) <lang mathematica>{1,2,3,4,5} // Total[#^2] &</lang> Pure function 2: <lang mathematica>{1, 2, 3, 4, 5} // #^2 & // Total</lang> Pure function 3: <lang mathematica>{1, 2, 3, 4, 5} // #.#&</lang>

MATLAB

<lang Matlab>function [squaredSum] = sumofsquares(inputVector)

  squaredSum = sum( inputVector.^2 );</lang>

Maxima

<lang maxima>nums : [3,1,4,1,5,9]; sum(nums[i]^2,i,1,length(nums));</lang>

Modula-3

<lang modula3>MODULE SumSquares EXPORTS Main;

IMPORT IO, Fmt;

TYPE RealArray = ARRAY OF REAL;

PROCEDURE SumOfSquares(x: RealArray): REAL =

 VAR sum := 0.0;
 BEGIN
   FOR i := FIRST(x) TO LAST(x) DO
     sum := sum + x[i] * x[i];
   END;
   RETURN sum;
 END SumOfSquares;

BEGIN

 IO.Put(Fmt.Real(SumOfSquares(RealArray{3.0, 1.0, 4.0, 1.0, 5.0, 9.0})));
 IO.Put("\n");

END SumSquares.</lang>

Objeck

<lang objeck> bundle Default {

 class Sum {
   function : native : SquaredSum(values : Float[]) ~ Float {
      sum := 0.0;
      for(i := 0 ; i < values->Size()	; i += 1;) {
        sum += (values[i] * values[i]);
      };
      
      return sum;
   }
   function : Main(args : String[]) ~ Nil {
      SquaredSum([3.0, 1.0, 4.0, 1.0, 5.0, 9.0])->PrintLine();
    }
 }

} </lang>

OCaml

<lang ocaml>List.fold_left (fun sum a -> sum + a * a) 0 ints</lang>

<lang ocaml>List.fold_left (fun sum a -> sum +. a *. a) 0. floats</lang>

Octave

<lang octave>a = [1:10]; sumsq = sum(a .^ 2);</lang>

Oz

<lang oz>declare

 fun {SumOfSquares Xs}
    for X in Xs sum:S do
       {S X*X}
    end
 end

in

 {Show {SumOfSquares [3 1 4 1 5 9]}}</lang>

PARI/GP

<lang>ss(v)={

 sum(i=1,#v,v[i]^2)

};</lang>

Perl

<lang perl>sub sum_of_squares {

 my $sum = 0;
 $sum += $_**2 foreach @_;
 return $sum;

}

print sum_of_squares(3, 1, 4, 1, 5, 9), "\n";</lang> or <lang perl>use List::Util qw(reduce); sub sum_of_squares {

 reduce { $a + $b **2 } 0, @_;

}

print sum_of_squares(3, 1, 4, 1, 5, 9), "\n";</lang>

Perl 6

Works with: Rakudo version #21 "Seattle"

<lang perl6>say [+] map * ** 2, 3, 1, 4, 1, 5, 9;</lang>

If this expression seems puzzling, note that * ** 2 is equivalent to {$^x ** 2}— the leftmost asterisk is not the multiplication operator but the Whatever star, which specifies currying behavior. Another convenient way to distribute the exponentiation is via the cross metaoperator, which as a list infix is looser than comma in precedence but tighter than the reduction list operator:

<lang perl6>say [+] 3,1,4,1,5,9 X** 2</lang>

PHP

<lang php> function sum_squares(array $args) {

   return array_reduce(
       $args, create_function('$x, $y', 'return $x+$y*$y;'), 0
   );

} </lang>

In PHP5.3 support for anonymous functions was reworked. While the above code would still work, it is suggested to use

<lang php> function sum_squares(array $args) {

   return array_reduce($args, function($x, $y) { 
       return $x+$y*$y;
   }, 0);

} </lang> Usage for both examples: sum_squares(array(1,2,3,4,5)); // 55

PicoLisp

<lang PicoLisp>: (sum '((N) (* N N)) (3 1 4 1 5 9)) -> 133

(sum '((N) (* N N)) ())

-> 0</lang>

PL/I

<lang PL/I> declare A(10) float initial (10, 9, 8, 7, 6, 5, 4, 3, 2, 1);

put (sum(A**2)); </lang>

Pop11

<lang pop11>define sum_squares(v);

   lvars s = 0, j;
   for j from 1 to length(v) do
       s + v(j)*v(j) -> s;
   endfor;
   s;

enddefine;

sum_squares({1 2 3 4 5}) =></lang>

PostScript

<lang> /sqrsum{ /x exch def /sum 0 def /i 0 def x length 0 eq {} { x length{ /sum sum x i get 2 exp add def /i i 1 add def }repeat }ifelse sum == }def </lang>

PowerShell

<lang powershell>function Get-SquareSum ($a) {

   if ($a.Length -eq 0) {
       return 0
   } else {
       $x = $a `
            | ForEach-Object { $_ * $_ } `
            | Measure-Object -Sum
       return $x.Sum
   }

}</lang>

PureBasic

<lang PureBasic>Procedure SumOfSquares(List base())

 ForEach base()
   Sum + base()*base()
 Next
 ProcedureReturn Sum

EndProcedure</lang>

Python

<lang python>sum(x*x for x in [1, 2, 3, 4, 5])</lang>

Prolog

   sum([],0).
   sum([H|T],S) :- sum(T, S1), S is S1 + (H * H).

R

<lang r>arr <- c(1,2,3,4,5) result <- sum(arr^2)</lang>

REXX

<lang rexx> /*REXX program to sum the squares of a vector. */

numeric digits 20 /*allow 20-digit numbers (default is 9)*/

v= /*start with a null vector. */

 do j=1 for 30              /*build an array of thirty elements.   */
 v=v j                      /*builds a vector: 1 2 3 ... 28 29 30  */
 end



sum=0 /*initialize SUM to zero. */

 do k=1                     /*start with the first element (if any)*/
 x=word(v,k)                /*pick off the  Kth  vector element.   */
 if x== then leave        /*if no more elements, then we're done.*/
 sum =sum + x**2            /*add the squared element to the sum.  */
 end

say 'sum of' k-1 "elements for the V vector is:" sum </lang> Output:

sum of 30 elements for the V vector is: 9455

Ruby

<lang ruby>[3,1,4,1,5,9].inject(0) { |sum,x| sum += x*x }</lang>

In 1.9.1 <lang ruby>[3,1,4,1,5,9].map { |x| x*x }.reduce(:+)</lang>

Sather

<lang sather>class MAIN is

 sqsum(s, e:FLT):FLT is
   return s + e*e;
 end;
 sum_of_squares(v :ARRAY{FLT}):FLT is
   return (#ARRAY{FLT}(|0.0|).append(v)).reduce(bind(sqsum(_,_)));
 end;
 main is
   v :ARRAY{FLT} := |3.0, 1.0, 4.0, 1.0, 5.0, 9.0|;
   #OUT + sum_of_squares(v) + "\n";
 end;

end;</lang>

Scala

Unfortunately there is no common "Numeric" class that Int and Double both extend, since Scala's number representation maps closely to Java's. Those concerned about precision can define a similar procedure for integers.

<lang scala>def sum_of_squares(xs: Seq[Double]) = xs.foldLeft(0) {(a,x) => a + x*x}</lang>

Scheme

<lang scheme>(define (sum-of-squares l)

 (apply + (map * l l)))</lang>
> (sum-of-squares (list 3 1 4 1 5 9))
133

Slate

<lang slate>{1. 2. 3} reduce: [|:x :y| y squared + x]. {} reduce: [|:x :y| y squared + x] ifEmpty: [0].</lang>

Smalltalk

<lang smalltalk>#(3 1 4 1 5 9) inject: 0 into: [:sum :aNumber | sum + aNumber squared]</lang>

SNOBOL4

Works with: Macro Spitbol
Works with: Snobol4+
Works with: CSnobol

<lang SNOBOL4> define('ssq(a)i') :(ssq_end) ssq i = i + 1; ssq = ssq + (a * a) :s(sumsq)f(return) ssq_end

  • # Fill array, test and display
       str = '1 2 3 5 7 11 13 17 19 23'; a = array(10)

loop i = i + 1; str len(p) span('0123456789') . a @p :s(loop)

       output = str ' -> ' sumsq(a)

end</lang>

Output:

 1 2 3 5 7 11 13 17 19 23 -> 1557

Standard ML

<lang sml>foldl (fn (a, sum) => sum + a * a) 0 ints</lang>

<lang sml>foldl (fn (a, sum) => sum + a * a) 0.0 reals</lang>

SQL

<lang sql>select sum(x*x) from vector</lang>

Note that this assumes that the values in our vector are named x.

Tcl

<lang tcl>proc sumOfSquares {nums} {

   set sum 0
   foreach num $nums {
       set sum [expr {$sum + $num**2}]
   }
   return $sum

} sumOfSquares {1 2 3 4 5} ;# ==> 55 sumOfSquares {} ;# ==> 0</lang>

Library: Tcllib (Package: struct::list)

<lang tcl>package require struct::list

proc square x {expr {$x * $x}} proc + {a b} {expr {$a + $b}} proc sumOfSquares {nums} {

   struct::list fold [struct::list map $nums square] 0 +

} sumOfSquares {1 2 3 4 5} ;# ==> 55 sumOfSquares {} ;# ==> 0</lang> Generic "sum of function" <lang tcl>package require Tcl 8.5 package require struct::list namespace path ::tcl::mathop

proc sum_of {lambda nums} {

   struct::list fold [struct::list map $nums [list apply $lambda]] 0 +

}

sum_of {x {* $x $x}} {1 2 3 4 5} ;# ==> 55</lang>

Trith

<lang trith>[3 1 4 1 5 9] 0 [dup * +] foldl</lang>

UnixPipes

<lang bash>folder() {

  (read B; res=$( expr $1 \* $1 ) ; test -n "$B" && expr $res + $B || echo $res)

}

fold() {

  (while read a ; do
      fold | folder $a
  done)

}


(echo 3; echo 1; echo 4;echo 1;echo 5; echo 9) | fold</lang>

Ursala

The ssq function defined below zips two copies of its argument together, maps the product function to all pairs, and then sums the result by way of the reduction operator, -:. <lang Ursala>#import nat

ssq = sum:-0+ product*iip

  1. cast %n

main = ssq <21,12,77,0,94,23,96,93,72,72,79,24,8,50,9,93></lang> output:

62223

V

<lang v>[sumsq [dup *] map 0 [+] fold].

[] sumsq =0 [1 2 3] sumsq</lang>

=14

Visual Basic .NET

<lang vbnet>

Private Shared Function sumsq(ByVal i As ICollection(Of Integer)) As Integer
       If i Is Nothing OrElse i.Count = 0 Then
           Return 0
       End If
       Return i.[Select](Function(x) x * x).Sum()
End Function
Private Shared Sub Main()
       Dim a As Integer() = New Integer() {1, 2, 3, 4, 5}
       ' 55
       Console.WriteLine(sumsq(a))

       For K As Integer = 0 To 16
              Console.WriteLine("SumOfSquares({0}) = {1}", K, SumOfSquares(K))
       Next
End Sub
Function SumOfSquares(ByVal Max As Integer)
       Dim Square As Integer = 0
       Dim Add As Integer = 1
       Dim Sum As Integer = 0
       For J As Integer = 0 To Max - 1
           Square += Add
           Add += 2
           Sum += Square
       Next
       Return Sum
End Function
Function SumOfSquaresByMult(ByVal Max As Integer)
       Dim Sum As Integer = 0
       For J As Integer = 1 To Max
           Sum += J * J
       Next
       Return Sum
End Function

</lang> output:

55
SumOfSquares(0) = 0
SumOfSquares(1) = 1
SumOfSquares(2) = 5
SumOfSquares(3) = 14
SumOfSquares(4) = 30
SumOfSquares(5) = 55
SumOfSquares(6) = 91
SumOfSquares(7) = 140
SumOfSquares(8) = 204
SumOfSquares(9) = 285
SumOfSquares(10) = 385
SumOfSquares(11) = 506
SumOfSquares(12) = 650
SumOfSquares(13) = 819
SumOfSquares(14) = 1015
SumOfSquares(15) = 1240
SumOfSquares(16) = 1496