Count subarrays having sum modulo K same as the length of the subarray | Java program for the above approach ; Function that counts the subarrays having sum modulo k equal to the length of subarray ; Stores the count of subarrays ; Stores prefix sum of the array ; Calculate prefix sum array ; Generate all the subarrays ; Check if this subarray is a valid subarray or not ; Total count of subarrays ; Driver Code ; Given arr [ ] ; Size of the array ; Given K ; Function call
import java . util . * ; import java . lang . * ; import java . io . * ; class GFG { static void countSubarrays ( int a [ ] , int n , int k ) { int ans = 0 ; ArrayList < Integer > pref = new ArrayList < > ( ) ; pref . add ( 0 ) ; for ( int i = 0 ; i < n ; i ++ ) pref . add ( ( a [ i ] + pref . get ( i ) ) % k ) ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = i ; j <= n ; j ++ ) { if ( ( pref . get ( j ) - pref . get ( i - 1 ) + k ) % k == j - i + 1 ) { ans ++ ; } } } System . out . println ( ans ) ; } public static void main ( String [ ] args ) throws java . lang . Exception { int arr [ ] = { 2 , 3 , 5 , 3 , 1 , 5 } ; int N = arr . length ; int K = 4 ; countSubarrays ( arr , N , K ) ; } }