... 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:  <%-{-{-{-<


In reply to Re: Anonymous Subroutine by AnomalousMonk
in thread Anonymous Subroutine by mimiv89

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.