views:

307

answers:

4

please help to print series as well sum of series like 1*3-3*5+5*7 up to n terms i have used code like this in php

class series {
    function ser(){
        $i = 0;
        $k = 3;
        $m = 0;

        for($j = 1; $j < 3; $j++) {
            if($j % 2 == 0 ) {
                $m = $i + ($i * $k);
            } else {
                $m=$m-($i*$k);

            }
        }

        //$m = $m + $i;
        echo "$m";
    }
}

$se = new series();
$se->ser();

Just i have tested for 2 times

+5  A: 

This is probably homework, but here goes anyway. Hopefully you learn something from this.

The code above is horrible. Over-complicated for nothing... Here's a very simple version for you. I have no idea of what language this is in, but I'll do something similar for you... Go get a book on programming, that will be a wise investment of your time.

function my_sum(int $count) {
    $result = 0;
    $sign = 1;
    for ($i=1; $i<=$count; $i++) {
        $result = $result + $sign * (2*$i-1) * (2*$i+1);
        $sign = - $sign;
    }
    return $result;
}

Hope this helps... You probably get the idea with this.

thanks it solve my prob
Rajanikant
You realise he probably just copy/pasted this answer without reading it or understanding it?
Charlie Somerville
Hope not for his own sake...
+5  A: 

I prefer the recursive function and by this way you can stackoverflow (woot!) :) :

public static int serie(int n){
 if(n<1){
  return 0;
 }else{
  return (n%2==0?-1:1)*(4*n*n-1)+serie(n-1);
 }
}
Pascal Le Clech
Excellent! mod +1 funny :)
+1  A: 

Hi

Or, use the following to compute the first n terms of your series. Sorry haven't figured out how to make SO display LaTeX properly, perhaps someone can edit it for me, but if you do please leave a comment with instructions please !

\frac{1}{2} \left(-4 (-1)^n n^2-4 (-1)^n n+(-1)^n-1\right)

Or, as generated by the wonderful EquationSheet.com:

alt text

Regards

Mark

High Performance Mark
I hope you find that site as helpful as I do, Mark. Just paste in your LaTeX, copy the URL of the generated image, and add it to your SO posting as an image. Brilliant stuff.
duffymo
+6  A: 

With a few simple operations one can find a formula for the sum S. If n is even (sum Se) adding pairs of terms yields

 Se = (1*3 - 3*5) + (5*7 - 7*9) + (9*11 - 11*13) ...
 Se = -4*(  3 + 7 + 11 + ...  )

The terms in the parenthesis can be splitted and summed up:

 Se = -4*( 1+2 + 3+4 + 5+6 + ...  )
 Se = -4*( n*(n+1)/2 )
 Se = -2*n*(n+1)

If n is odd (sum So) the last term must be added to Se:

 So = Se + 4*n*n-1
 So = +2*n*(n+1) - 1

The implementation in C:

int series ( unsigned int n )
{
  if ( n%2 == 0 )
    return -2*n*(n+1);
  else
    return +2*n*(n+1) - 1;
}
fgm
Doing some math on paper before rushing to implement tons of loops : that's real optimisation !
siukurnin