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

Hiya, monks

So, I'm stuck on a really dumb part of the program I'm working on. What I wanna do is for every number from 1 to 1000, i want to add and subtract alternately using a subroutine.

Ex. 1-2+3-4+5-6+7-8+9-10 and so on. Thanks for the help!
  • Comment on stupid question about switching signs every number

Replies are listed 'Best First'.
Re: stupid question about switching signs every number
by Marshall (Canon) on Aug 17, 2010 at 21:08 UTC
    #!/usr/bin/perl -w use strict; my $sum=0; foreach my $num (1..1000) { if ($num % 2) #odd { $sum += $num } else #even { $sum -= $num; } } print $sum;
    It is possible to write a closed form expression that generates $sum for any X without using a computing loop. I leave that part of your homework for you to figure out.
Re: stupid question about switching signs every number
by kennethk (Abbot) on Aug 17, 2010 at 21:16 UTC
    In addition to Marshall's suggestion, I offer up:
    • Abusive one-liner:

      my $sum = 0; $sum += (-1)**($_+1) * $_ for 1 .. 1000; print "$sum\n";
    • More logical:

      my $sum = 0; my $sign = 0; for my $i (1 .. 1000) { $sum += ($sign ? -1 : 1) * $i; $sign = !$sign; } print $sum;
    • or:

      my $sum = 0; my $sign = 0; for my $i (1 .. 1000) { $sum += ($sign++ % 2 ? -1 : 1) * $i; } print $sum;
    • Smart:

      my $sum = 0.5*(1 + 999)*( (999-1)/2 + 1 ) - 0.5*(2 + 1000)*( (1000-2)/ +2 + 1 ); print $sum;

    Of course, "Smart" can yield round-off issues...

      Why use a boolean to represent a sign?

      my $sum = 0; my $sign = 1; for my $i (1 .. 1000) { $sum += $sign * $i; $sum*=-1; } print $sum;

      Rule One: "Do not act incautiously when confronting a little bald wrinkly smiling man."

Re: stupid question about switching signs every number
by jwkrahn (Abbot) on Aug 17, 2010 at 22:32 UTC
    $ perl -le' $_ = join "+", 1 .. 10; print; s/\+(\d+(?:\+|$))/-$1/g; pr +int; print eval' 1+2+3+4+5+6+7+8+9+10 1-2+3-4+5-6+7-8+9-10 -5
Re: stupid question about switching signs every number
by aquarium (Curate) on Aug 17, 2010 at 23:12 UTC
    This is one of many times similar homework type questions have been asked, without providing any proof whatsoever of an attempt of any kind. Perlmonks are being too generous in offering code, so that Derpp will never get past break in stage into perl. This forum is not a free homework service.
    the hardest line to type correctly is: stty erase ^H
Re: stupid question about switching signs every number
by JavaFan (Canon) on Aug 17, 2010 at 22:03 UTC
    Well, considering that you have 500 pairs of the form (n) - (n + 1), which you are all adding, I'd do:
    sub sum_alternating {-1 * 500}