Alternating Sign Series 1 - 2 + 3 - 4 ...
Problem
Read n and print the value of 1 - 2 + 3 - 4 + ... up to the number n. Odd numbers are added and even numbers are subtracted. For n = 0 the result is 0.
Constraints
- 0 <= n <= 10^9
Examples
Input
5
Output
3
Solutions
We visit each number and decide the sign with the remainder of the division by 2.
/*
* Problem : Find 1 - 2 + 3 - 4 + ... up to n.
* Input : One integer n (n >= 0).
* Output : The result.
* Approach: Add or subtract each number in a loop.
* Time : O(n)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int n = new Scanner(System.in).nextInt();
// Step 1: The result starts at 0.
long result = 0;
// Step 2: Visit the numbers from 1 to n.
for (int number = 1; number <= n; number++) {
// Step 3: Add odd numbers and subtract even numbers.
if (number % 2 == 1) {
result = result + number;
} else {
result = result - number;
}
}
// Step 4: Print the result.
System.out.println(result);
}
}
Hints (1)
- Which numbers get a plus sign?