I'm sorry I am sort of new to coding, but I've been asked to take an integer as input for the nth term and print out the value from this pattern, and I have written something that works however I feel as though I am severely over complicating things. Here is the series in question:
y = -(1)-(1+2)+(1+2+3)+(1+2+3+4)-(1+2+3+4+5) .... (1+2+3+4...+n)
Here is the code:
import java.util.Scanner;
public class wontwork {
public static void main(String[] args) {
Scanner np = new Scanner(System.in);
System.out.println("Enter n");
int n = np.nextInt();
int count = 1;
int sum = 0;
int y = 0;
for(int i = 1; i<=n ; i+=2) {
if(count%2==0) {
sum+=i;
y+=sum;
sum+=i+1;
y+=sum;
}
else {
sum+=i;
y-=sum;
sum+=i+1;
y-=sum;
}
count++;
}
if(n%2!=0) {
if (count%2==0) {
System.out.print(y+sum);
}
else {
System.out.print(y-sum);
}
}
else {
System.out.print(y);
}
np.close();
}
}
A sample output should give 12 when input 4 and -3 when input 5.
As I understand it is subtracting twice and adding twice the sum of the values. And what I have done is made a for loop and taken a count variable that checks whether to first add or subtract depending on whether it is odd or even and then took a sum variable to calculate the values each iteration in between the brackets and added or subtracted that to y.
But for every time the loop runs, this process happens twice. So y is added by -(1) and -(1+2) the first loop when the count is odd and then by (1+2+3) and (1+2+3+4) on the next when the count is even. I did that because if I add say (1+2+3) individually the count being even, I have to also add (1+2+3+4) and increment the count, however, that makes it odd, and it is no longer useful for using that to either add or subtract. I would hate if I am missing something obvious but I cannot figure out for the life of me how else to know when its incremented twice to then make it either positive or negative.
For this reason, also, if not for the if else statement at the end, the program just outputs the correct values for every 2n and to fix that I took the last stored sum value and checked whether count is odd or even and then added or subtracted again with y it to find the middle value for n. Apologies if I've not written or formatted anything incorrectly since this is my first post here but please let me know what else I can do. I would appreciate any help.
I have written something that works however I feel as though I am severely over complicating things.
Looks like you want to subtract two terms, add two terms, subtract two terms eventually subtracting or adding one or two terms as appropriate.
The easiest way, imo, is to use the arithemetic sum formula
for 1 + 2 + 3 + 4 .. + n which is ((n+1)*n)/2
. When i
becomes even, reverse the sign.
int n = 4;
int sum = 0;
int sign = -1;
for (int i = 1; i <= n; i++) {
sum += sign*((i+1)*i)/2;
if (i % 2 == 0) {
sign = -sign;
}
}
System.out.println(sum);
prints
12