 Don't ask to ask, just ask PerlMonks

### Anonymous Subroutine

by mimiv89 (Initiate)
 on Nov 27, 2017 at 01:58 UTC Need Help??

mimiv89 has asked for the wisdom of the Perl Monks concerning the following question:

How can I create an anonymous subroutine that can calculate the sum of 1^2 + 2^2 + 3^2 + �. + n^2,(these are exponents) where n is passed by a reference, \$p. so far I have this but don't know if this is correct or what i need to change/modify: please help

```use CGI qw(:standard);
print start_html;
print "<form action='\$ENV{SCRIPT_NAME}' method='post'>";
print "Enter an integer: <input type='text' name='n'>";
print "<input type='submit' value='Submit'>";
print "</form>";

if (param)
{
\$n = param('n');
\$p = sub
{
\$sum = 1**2+2**2+3**2+4**2+5**2+6**2+7**+\$n**2;
for ('\$i=0; <= \$n; \$i++')
{
\$sum += \$i;
}
return \$sum;
};
print \$p->(\$n);
}
print end_html;

I have no errors but I feel like my calculation is wrong the results is not what it should be, why?

Replies are listed 'Best First'.
Re: Anonymous Subroutine
by BillKSmith (Prior) on Nov 27, 2017 at 04:34 UTC
It is faster and less error prone to use the summation formula rather than doing the brute force summation.
```use strict;
use warnings;
my \$number = \$ARGV;
my \$sum_of_squares = sub{
my \$n = shift;
return \$n * (\$n + 1) * (2*\$n +1) / 6;
};

print \$sum_of_squares->(\$number);

This formula is available in many places. I first found it at https://brilliant.org/wiki/sum-of-n-n2-or-n3/.

Bill
Re: Anonymous Subroutine
by NetWallah (Canon) on Nov 27, 2017 at 02:28 UTC
```use strict;
use warnings;

my \$n = shift or die "Need 'n' as param";

my \$anon_sub = sub{
my \$count=shift @_;
my \$sum_sqares=0;
for my \$i(1..\$count){
\$sum_sqares += \$i**2;
}
return \$sum_sqares;
}; # CLose anon sub

print "N=\$n, sum squares=", \$anon_sub->(\$n),"\n";
Update: See BillKSmith's (++) More algebra-savvy, and faster solution below.

All power corrupts, but we need electricity.

Thank you so much this worked perfectly.

Re: Anonymous Subroutine
by AnomalousMonk (Bishop) on Nov 27, 2017 at 02:59 UTC
... calculate the sum of 1^2 + 2^2 + 3^2 + …. + n^2,(these are exponents) ...
\$sum = 1**2+2**2+3**2+4**2+5**2+6**2+7**+\$n**2;
... my calculation is wrong the results is not what it should be, why?

You've left out the …. part of the summation specification from the
\$sum = 1**2+2**2+3**2+4**2+5**2+6**2+7**+\$n**2;
statement (update: which is in error in any event: what is the  7**+\$n**2 term supposed to represent?). If n were 15, where are 8, 9, 10, 11, 12, 13, 14 in the sequence of numbers to be squared and summed?

```c:\@Work\Perl\monks>perl -wMstrict -le
"use Data::Dump qw(dd);
use List::Util qw(sum reduce);
;;
my \$n = 15;
dd                1 .. \$n;
dd     map \$_**2, 1 .. \$n;
dd sum map \$_**2, 1 .. \$n;
;;
use vars qw(\$a \$b);
dd reduce { \$a + \$b**2 } 1 .. \$n;
"
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)

(1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225)

1240

1240
I haven't tested it, but NetWallah's solution looks right.

Update: See Range Operators in perlop for the  .. operator in list context.

Update 2: I actually missed the whole

``` for ('\$i=0; <= \$n; \$i++')
{
\$sum += \$i;
}
piece of the OPed code, but that's ok because without strictures and warnings enabled, it's just a no-op in the final execution. :)

Update 3: Changed example code to use ranges of  1 .. \$n with  \$n initialized to 15 instead of literal  1 .. 15 ranges; makes the point a little better. Also added the reduce example.

Give a man a fish:  <%-{-{-{-<

Create A New User
Node Status?
node history
Node Type: perlquestion [id://1204303]
Approved by holli
Front-paged by haukex
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (5)
As of 2020-01-21 04:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
The worst excuse I have ever heard is:

Results (95 votes). Check out past polls.

Notices?