Wrong Answer in Compute F(n)

Hi,

I am trying to solve this problem using Arithmetic progression approach :

f(n) = n/2 (2A + (n-1) .d) and divided the series into positive and negative parts.

Please check the approach if there’s anything wrong in it.

Thanks.

1 Like

Hy pradeep,
I have corrected your code

import java.util.*;
public class Main {
    public static void main(String args[]) {
        solve();
    }

    private static void solve() {
        Scanner scanner = new Scanner(System.in);
        int test = scanner.nextInt();

        while (test-- > 0) {

            long n = scanner.nextLong();
            long result;

            if ((n & 1) != 0) {
                long posNum =  n / 2;
                long negNum = (n / 2 + 1);

                result = -(long)((long)(negNum) * (2 + (long)((negNum - 1) * 2)))/2 +
                        (long)(posNum *(long) (4 + (posNum - 1) * 2))/2;
            } else {
                long posNum = (long) (n / 2);
                long negNum = (long) (n / 2);

                result = -(long)(negNum * (long)(2 +(long)( (negNum - 1) * 2)))/2 +
                        (long)(posNum *(long) (2 * 2 +(long)((posNum - 1) * 2)))/2;
            }

            System.out.println(result);
        }

    }
}

There were some simple type casting issues and some division compatibility problems . Please refer your old code and mark out the changes i have done for better clarity

1 Like