0

The program begins by asking the user to give a value assigned to variable n, the user will then be prompted to submit long digits n amounts of times. The digits will then be stored into the initialized array (ar). The function I am trying to create aVeryBigSum is to loop through the numbers in the array, incrementing sum=0 by the numbers in the array to provide the sum (Java).

For some reason however, the program works unless I use two consecutive numbers with greater than 9 digits.

For example:

aVeryBigSum(2,[111111111,111111111]) has n of 2 and two 9 digit numbers in the array

Output:

22222222

aVeryBigSum(2,[1111111111,1111111111]) has n of 2 and two 10 digit numbers in the array Output:

-2072745074

Any idea what the issue might be? I've provided the program below:

import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Main {

    static long aVeryBigSum(int n, long[] ar) {
        int sum  = 0;
        for (int i = 0; i < n; i++){
          System.out.println(sum);
          System.out.println(ar[i]);
          sum += ar[i];
          System.out.println(" ");
        }
        return sum;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        long[] ar = new long[n];
        for(int ar_i = 0; ar_i < n; ar_i++){
            ar[ar_i] = in.nextLong();
        }
        long result = aVeryBigSum(n, ar);
        System.out.println(result);
    }
}
Juan Carlos Mendoza
  • 5,736
  • 7
  • 25
  • 50
RacketyGnome300
  • 77
  • 2
  • 2
  • 7

2 Answers2

1

Your problem is in the line

int sum  = 0;

It should read

long sum = 0;

You are triggering integer overflow when the sum of integers exceeds 32 bits.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
0

Yes, agree with Mad Physicist. You have to use long sum = 0. But to be the completely correct, you have possibility to have sum greater than Long.MAX_VALUE. You could use e.g. BigDecimal:

static BigDecimal aVeryBigSum(int n, long[] ar) {
    BigDecimal sum = BigDecimal.ZERO;

    for (int i = 0; i < n; i++) {
        System.out.println(sum);
        System.out.println(ar[i]);

        sum = sum.add(new BigDecimal(ar[i]));

        System.out.println(" ");
    }

    return sum;
}
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35