-2

This code calculates the function f(x) = -1 + 2 + -3 + 4 + ... + (( - 1)^n)*n But when the input(n) is too big, like 1000000000, java doesn't display an output.

What can I do to solve this problem?

import java.util.Scanner;

public class Calculating_function {
    public static void main(String[] args) {



        Scanner input_taker = new Scanner(System.in);

        String n_string = input_taker.nextLine();
        long n = Long.parseLong(n_string);



        System.out.println(fonk(n));


    }

    public static long fonk(long n) {
        long total = 0;
        for(long i = 1; i <= n; i++) {

            total += (long)Math.pow(-1, i) * i; 
        }
        return total;
    }
Babak Naffas
  • 12,395
  • 3
  • 34
  • 49

1 Answers1

2

As the value of i increases, your exponent calculation Math.pow(-1, i) will take longer and longer to calculate.

As you're using Math.pow(-1, i) to simply swap the sign, you can optimize it as Math.pow(-1, i%2). Better yet, map the multiplier to the values 1 and -1 and use i%2 as your key.

Additionally, you are risking overflows as your total has an upper bound of 500,000,000,000,000,000 so use BigInteger instead to store the total.

Babak Naffas
  • 12,395
  • 3
  • 34
  • 49