Sum of squares: Difference between revisions
Content added Content deleted
(page creation) |
(Added Java example.) |
||
Line 17: | Line 17: | ||
ss x |
ss x |
||
9.09516 5.19512 5.84173 6.6916 |
9.09516 5.19512 5.84173 6.6916 |
||
=={{header|Java}}== |
|||
Assume the numbers are in an array called "nums". |
|||
... |
|||
int sum = 0; |
|||
for(int a:nums){ |
|||
sum+= a * a; |
|||
} |
|||
System.out.println("The sum of the squares is: " + sum); |
|||
... |
Revision as of 17:55, 11 December 2007
Sum of squares
You are encouraged to solve this task according to the task description, using any language you may know.
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).
J
ss=: +/ @: *:
That is, sum composed with square. The verb also works on higher-ranked arrays. For example:
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
Java
Assume the numbers are in an array called "nums".
... int sum = 0; for(int a:nums){ sum+= a * a; } System.out.println("The sum of the squares is: " + sum); ...