Page 1 of 1

Creating infinite series

Posted: Mon Oct 20, 2008 3:35 pm UTC
So new to coding, in my php programming class and we are told to pretty much create an infinite series. The whole:
1 = 1,
1 − 2 = −1,
1 − 2 + 3 = 2,
1 − 2 + 3 − 4 = −2,
1 − 2 + 3 − 4 + 5 = 3,
1 − 2 + 3 − 4 + 5 − 6 = −3
and so on...

up until the answer is 10, and down to -10

No idea, i don't want the exact code, of course. But maybe a bit of help in getting started?

Re: Creating infinite series

Posted: Mon Oct 20, 2008 4:03 pm UTC
What *exactly* do you need to do? If you need to print each step of the series, or just the answers, or just put it in a data structure and manipulate it, the answers are a bit different.

Re: Creating infinite series

Posted: Mon Oct 20, 2008 5:57 pm UTC
You can generate any particular element in a list by using a for loop. You can make it increment by two instead of one, and then the difficulty is on the same level as "print the numbers one through ten".

Re: Creating infinite series

Posted: Tue Oct 21, 2008 3:23 pm UTC
Well yeah, you could easily fake it with something like:

Code: Select all

(Pseudocode):For all values between 1 and 10:     Print value     Print "-" + value

That is Print the numbers from 1 to ten and after each one print that number with a negative sign before it

However, that's probably not what you're supposed to do. But, as posted, you will probably want to use a loop. searching "for loop PHP" on google should get you info on how to use them (or your textbook could help )

To determine, in your code, whether or not you're adding or subtracting, you could do a couple of different things. either something like: always adding and multiplying by -1 every time. or if (i % 2) == 0 then subtract instead of adding. or adding pow(-1,i+1) * i each time. In each of these cases, i is the value incremented by the for loop, or whatever.

Well, I hope this is enough to get you started. Good luck, and let us know if you still need some help.

~ Chibu

Re: Creating infinite series

Posted: Tue Oct 21, 2008 9:07 pm UTC
Uh, I have no idea what the actual question is, but because I'm bored, here's a "shortcut" formula: [imath]-(-1)^n (\frac {n+\frac {1}{2}(1-(-1)^n)}{2})[/imath]

Re: Creating infinite series

Posted: Wed Oct 22, 2008 11:47 am UTC

Code: Select all

n=((i&1)?1:-1)*(((i+1)>>1)); /* for i from 1 to 20, both included */

Yet another stupid way to get it. I am pretty sure they are asking you to use recursive functions, even if it is going to take ages for high values of i. Else, the best algorithm is the one by chibu.
EDIT:Also:
Spoiler:

Code: Select all

                printf("1"); /* in your previous loop */                for(j=2;j<=i;j++){                        printf((j&1)?"+%d":"-%d",j);                }                printf("=%d\n",n);