Codeforces 486A Calculating Function Solution & Explanation

Difficulty : 800

Problem Description

For a positive integer n let’s define a function f:

f(n) =  - 1 + 2 - 3 + .. + ( - 1)nn

Your task is to calculate f(n) for a given integer n.

Input

The single line contains the positive integer n (1 ≤ n ≤ 1015).

Output

Print f(n) in a single line.

Eamples

Input4
Output2

f(4) = -1+2-3+4 = 2 

Input5
Output-3

f(5) = -1+2-3+4-5 = -3


Solution

In our first try, we use an iteration to calculate directly.

C# Solution

First try – Runtime error/ Time limit exceeded 

int n = int.Parse(Console.ReadLine());
int tmp = -1;
int res = 0;

for(int i=1; i<=n; i++){
    res+=tmp*i;
    tmp*=-1;
}

Console.WriteLine(res);

Solution1

long n = long.Parse(Console.ReadLine());

if(n%2==0)
{
    Console.WriteLine(n/2);
}
else{
    var res = (n/2)-n;
    Console.WriteLine(res);
}

We can find out every two consecutive numbers form a pair, one positive and one negative, and their sum is always 1. For example:

  • (−1+2)=1
  • (−3+4)=1
  • (−5+6)=1

Therefore, if the input n is even, the sum of n integers is n/2​ because each pair of numbers adds up to 1.

However, if n is odd, the last number remains, and the sum is the result of adding up the first n​ numbers minus this last number, which is (n/2)-n.

Java Solution

Solution1

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        long n = scanner.nextLong();
        
        if(n%2==0)
        {
            System.out.println(n/2);
        }
        else{
            System.out.println((n/2)-n);
        }
    }
}

Python3 Solution

Solution1

n = int(input())

if n%2 ==0:
    print(n//2)
else:
    print(n//2-n)

Python divide operator (/) will always return a float number, providing a decimal result.

However, if you need an integer result, you should use the floor division operator (//). The floor division ensures that the result is rounded down to the nearest integer.

JavaScript Solution

Solution1

var n = readline();

if (n % 2 === 0) {
    print(Math.floor(n/2));
} 
else {
    print(Math.floor(n/2)-n);
}

Use parseInt can achieve the same result, rounding down to the nearest integer.


Conclusion

🧡If my solution helps, that is my honor!

🧡You can support me by sharing my posts, thanks you~~

✅If you got any problem about the explanation or you need other programming language solution, please feel free to let me know !!

The problem link : Problem – 486A – Codeforces

Random Codeforces Posts

Leave a Reply

Your email address will not be published. Required fields are marked *