Divisible subarrays(one test case fail)

package competitive;

import java.util.*;

public class Pignhole_Principal {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
long arr[] = new long[n];

		for (int i = 0; i < arr.length; i++) {
			arr[i] = sc.nextLong();
		}
		System.out.println(sumofsubarray(arr, n));
	}
}

public static long sumofsubarray(long[] arr, int n) {

	long[] ans = new long[n];
	long sum = 0;
	ans[0] = 1;
	for (int i = 0; i < n; i++) {
		sum += arr[i];
		if (sum < 0) {
			int p = (int) ((sum + n) % n);
			ans[p]++;
		} else
			ans[(int) (sum % n)]++;
	}
	long fs = 0;

	for (int i = 0; i < n; i++) {
		if (ans[i] >= 2) {

			fs += (ans[i] * (ans[i] - 1)) / 2;
		}
	}
	return fs;

}

}

Hey @sk3657860,
Everything seems fine in your code but since elements of array can go from -10^9 upto 10^9 which can be much larger than n, so you need to take of modulo thing like, when sum becomes zero you are assuming that sum will never go down to -n , suppose sum becomes -(n+5), then p will be (-n-5+n)%n which is -5(assuming n is more than 5) and you are inserting negative value. Just correcting this modulo thing will get you AC.
if (sum < 0) {
int p = (int) ((sum + n) % n);
ans[p]++;
}

Refer this corrected code: https://ide.codingblocks.com/s/169888

Thanks,

You don’t need to reopen doubt again and again, simply reply here. TA’s would help you out

Hi @abhishek.171co203
Your code fails for
1
5
1 2 -3 1 4

Ans=4, should be 3.