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.

3

There are 3 best solutions below

0
WJS On BEST ANSWER

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
1
Albers Joy On

In your code, why do you choose i += 2 ? It makes your code complex. Here is a simplier 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 sum = 0;
    int y = 0;
    
    for(int i = 1; i<= n ; i ++) {
      
      sum += i;

      if(i % 4 == 1 || i % 4 == 2 ) {
        y -= sum;
      } else {
        y += sum;
      }
    }
    
    System.out.print(y);
    
    np.close();
  }
}

It will work correctly.

If I'm wrong, I'm sorry

0
Mike 'Pomax' Kamermans On

This starts life as a modelling problem. Ignore y = and look at what each step does: at step zero, -1. At step -1. At step 1, -(1+2). At step 2, +(1+2+3), At step 3, +(1+2+3+4). At step 4, -(1+2+3+4+5), etc. so at every step i we sum 1 through i+1, and so we need a simple statement that tells us what the sign needs to be without having to track it: 0=-, 1=-,2=+,3=+, 4=-, etc so the cycle repeats every 4 steps, so we start with i % 4, which is always positive, we need 2 terms to be negative, so i % 4 - 2 - except that'll give us -1, +1, or zero as possible signs, so we bias that just a tiny bit to i % 4 - 1.99 and now we'll get -1 or +1 for 0, 1, and 2, 3 respectively.

And then with that, we can calculate each step in the summation that yields y:

const { sign } = Math;

// sum function for 1+2+3+4+...+n
function sum(n) {
  // special case for zero:
  if (n===0) return { term: 0, why: `0` };

  // we already know the sum for 1:
  let term = 1;
  let why = `1`;

  // so we add terms only if n is 2 or higher.
  for (let i = 2; i <= n; i++) {
    term += i;
    why = `${why} + ${i}`;
  }

  // return the sum and the sequence we used:
  return {term, why};
}

// calculate the special summation
function calculateSum(n) {
  let y = 0;
  let explanation = ``;

  for (let i = 0; i < n; i++) {
    // calculate the sign we need for this "i":
    const s = sign(i % 4 - 1.99);

    // then calculate this step's sum term:
    const { term, why } = sum(i+1);

    // and then we update "y":
    y += s * term;

    // and because we're being fancy, also update
    // an explanation of how we calcualted this.
    explanation = `${explanation} ${s<0?`-`:`+`} (${why})`;
  }

  return {y, explanation};
}

// Calculate the sum given some input "n":
userInput.addEventListener(`change`, () => {
  const n = parseFloat(userInput.value);
  if (!isNaN(n)) {
   const { y, explanation } = calculateSum(n);

   sumResult.textContent = y;
   sumExplanation.textContent = explanation;
  } 
});
<input id="userInput" type="number" value="0"> is: <span id="sumResult">0</span>, computed as <span id="sumExplanation"></span>