Check if any valid sequence is divisible by M
Last Updated :
20 Dec, 2022
Given an array of N integers, using ‘+’ and ‘-‘ between the elements check if there is a way to form a sequence of numbers that evaluate to a number divisible by M
Examples:
Input: arr = {1, 2, 3, 4, 6}
M = 4
Output: True
Explanation:
There is a valid sequence i.e., (1 – 2
+ 3 + 4 + 6), which evaluates to 12 that
is divisible by 4
Input: arr = {1, 3, 9}
M = 2
Output: False
Explanation:
There is no sequence which evaluates to
a number divisible by M.
A simple solution is to recursively consider all possible scenarios ie either use a ;+’ or a ‘-‘ operator between the elements and maintain a variable sum which stores the result.If this result is divisible by M then return true else return false.
Recursive implementation is as follows:
C++
bool isPossible( int index, int sum)
{
if (index == n) {
if ((sum % M) == 0)
return true ;
return false ;
}
bool placeAdd = isPossible(index + 1,
sum + arr[index]);
bool placeMinus = isPossible(index + 1,
sum - arr[index]);
if (placeAdd || placeMinus)
return true ;
return false ;
}
|
Java
static boolean isPossible( int index, int sum)
{
if (index == n)
{
if ((sum % M) == 0 )
return true ;
return false ;
}
boolean placeAdd = isPossible(index + 1 ,
sum + arr[index]);
boolean placeMinus = isPossible(index + 1 ,
sum - arr[index]);
if (placeAdd || placeMinus)
return true ;
return false ;
}
|
Python3
def isPossible(index, sum ):
if (index = = n):
if (( sum % M) = = 0 ):
return True ;
return False ;
placeAdd = isPossible(index + 1 , sum + arr[index]);
placeMinus = isPossible(index + 1 , sum - arr[index]);
if (placeAdd or placeMinus):
return True ;
return False ;
|
C#
static bool isPossible( int index, int sum)
{
if (index == n)
{
if ((sum % M) == 0)
return true ;
return false ;
}
bool placeAdd = isPossible(index + 1,
sum + arr[index]);
bool placeMinus = isPossible(index + 1,
sum - arr[index]);
if (placeAdd || placeMinus)
return true ;
return false ;
}
|
Javascript
<script>
function isPossible(index , sum)
{
if (index == n)
{
if ((sum % M) == 0)
return true ;
return false ;
}
let placeAdd = isPossible(index + 1,
sum + arr[index]);
let placeMinus = isPossible(index + 1,
sum - arr[index]);
if (placeAdd || placeMinus)
return true ;
return false ;
}
</script>
|
There are overlapping subproblems as shown in the image below (Note: the image represents the recursion tree till index = 3)

Better Approach: To optimize the above approach use dynamic programming.
Method 1: We apply Dynamic Programming with two states :-
- index,
- sum
So DP[index][sum] stores the current index we are at and sum stores the result of evaluation of the sequence formed till that index.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
const int MAX = 1000;
bool isPossible( int n, int index, int sum,
int M, int arr[], int dp[][MAX])
{
if (index == n) {
if ((sum % M) == 0)
return true ;
return false ;
}
if (dp[index][sum] != -1)
return dp[index][sum];
bool placeAdd = isPossible(n, index + 1,
sum + arr[index], M, arr, dp);
bool placeMinus = isPossible(n, index + 1,
sum - arr[index], M, arr, dp);
bool res = (placeAdd || placeMinus);
dp[index][sum] = res;
return res;
}
int main()
{
int arr[] = { 1, 2, 3, 4, 6 };
int n = sizeof (arr)/ sizeof (arr[0]);
int M = 4;
int dp[n + 1][MAX];
memset (dp, -1, sizeof (dp));
bool res;
res = isPossible(n, 0, 0, M, arr, dp);
cout << (res ? "True" : "False" ) << endl;
return 0;
}
|
Java
import java.util.*;
class GFG
{
static final int MAX = 1000 ;
static boolean isPossible( int n, int index, int sum,
int M, int arr[], int dp[][])
{
if (index == n)
{
if ((sum % M) == 0 )
return true ;
return false ;
}
else if (sum < 0 || sum >= MAX)
return false ;
if (dp[index][sum] != - 1 )
{
if (dp[index][sum] == 0 )
return false ;
return true ;
}
boolean placeAdd = isPossible(n, index + 1 ,
sum + arr[index], M, arr, dp);
boolean placeMinus = isPossible(n, index + 1 ,
sum - arr[index], M, arr, dp);
boolean res = (placeAdd || placeMinus);
dp[index][sum] = (res) ? 1 : 0 ;
return res;
}
public static void main(String args[])
{
int arr[] = { 1 , 2 , 3 , 4 , 6 };
int n = arr.length;
int M = 4 ;
int dp[][] = new int [n + 1 ][MAX];
for ( int i = 0 ; i < n + 1 ; i++)
Arrays.fill(dp[i], - 1 );
boolean res;
res = isPossible(n, 0 , 0 , M, arr, dp);
System.out.println((res ? "True" : "False" ));
}
}
|
Python3
def isPossible(n, index, Sum , M, arr, dp):
global MAX
if index = = n:
if ( Sum % M) = = 0 :
return True
return False
if dp[index][ Sum ] ! = - 1 :
return dp[index][ Sum ]
placeAdd = isPossible(n, index + 1 ,
Sum + arr[index], M, arr, dp)
placeMinus = isPossible(n, index + 1 ,
Sum - arr[index], M, arr, dp)
res = placeAdd or placeMinus
dp[index][ Sum ] = res
return res
MAX = 1000
arr = [ 1 , 2 , 3 , 4 , 6 ]
n = len (arr)
M = 4
dp = [[ - 1 ] * MAX for i in range (n + 1 )]
res = isPossible(n, 0 , 0 , M, arr, dp)
if res:
print ( True )
else :
print ( False )
|
C#
using System;
class GFG
{
static int MAX = 1000;
static Boolean isPossible( int n, int index, int sum,
int M, int []arr, int [,]dp)
{
if (index == n)
{
if ((sum % M) == 0)
return true ;
return false ;
}
else if (sum < 0 || sum >= MAX)
return false ;
if (dp[index,sum] != -1)
{
if (dp[index,sum] == 0)
return false ;
return true ;
}
Boolean placeAdd = isPossible(n, index + 1,
sum + arr[index],
M, arr, dp);
Boolean placeMinus = isPossible(n, index + 1,
sum - arr[index],
M, arr, dp);
Boolean res = (placeAdd || placeMinus);
dp[index,sum] = (res) ? 1 : 0;
return res;
}
public static void Main(String []args)
{
int []arr = { 1, 2, 3, 4, 6 };
int n = arr.Length;
int M = 4;
int [,]dp = new int [n + 1, MAX];
for ( int i = 0; i < n + 1; i++)
for ( int j = 0; j < MAX; j++)
dp[i, j] = -1;
Boolean res;
res = isPossible(n, 0, 0, M, arr, dp);
Console.WriteLine((res ? "True" : "False" ));
}
}
|
Javascript
<script>
var MAX = 1000;
function isPossible(n , index , sum,M , arr , dp)
{
if (index == n)
{
if ((sum % M) == 0)
return true ;
return false ;
}
else if (sum < 0 || sum >= MAX)
return false ;
if (dp[index][sum] != -1)
{
if (dp[index][sum] == 0)
return false ;
return true ;
}
var placeAdd = isPossible(n, index + 1,
sum + arr[index], M, arr, dp);
var placeMinus = isPossible(n, index + 1,
sum - arr[index], M, arr, dp);
var res = (placeAdd || placeMinus);
dp[index][sum] = (res) ? 1 : 0;
return res;
}
var arr = [ 1, 2, 3, 4, 6 ];
var n = arr.length;
var M = 4;
var dp = Array(n+1).fill(-1).map(x => Array(MAX).fill(-1));
res = isPossible(n, 0, 0, M, arr, dp);
document.write((res ? "True" : "False" ));
</script>
|
Time Complexity: O(N*sum), where the sum is the maximum possible sum for the sequence of integers and N is the number of elements in the array.
Auxiliary Space: O(N * MAX), here MAX = 1000
Method 2(efficient): This is more efficient than Method 1. Here also, we apply Dynamic Programming but with two different states:
- index,
- modulo
So DP[index][modulo] stores the modulus of the result of the evaluation of the sequence formed till that index, with M.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
const int MAX = 100;
int isPossible( int n, int index, int modulo,
int M, int arr[], int dp[][MAX])
{
modulo = ((modulo % M) + M) % M;
if (index == n) {
if (modulo == 0)
return 1;
return 0;
}
if (dp[index][modulo] != -1)
return dp[index][modulo];
int placeAdd = isPossible(n, index + 1,
modulo + arr[index], M, arr, dp);
int placeMinus = isPossible(n, index + 1,
modulo - arr[index], M, arr, dp);
bool res = (placeAdd || placeMinus);
dp[index][modulo] = res;
return res;
}
int main()
{
int arr[] = { 1, 2, 3, 4, 6 };
int n = sizeof (arr)/ sizeof (arr[0]);
int M = 4;
int dp[n + 1][MAX];
memset (dp, -1, sizeof (dp));
bool res;
res = isPossible(n, 1, arr[0], M, arr, dp);
cout << (res ? "True" : "False" ) << endl;
return 0;
}
|
Java
class GFG
{
static int MAX = 100 ;
static int isPossible( int n, int index, int modulo,
int M, int arr[], int dp[][])
{
modulo = ((modulo % M) + M) % M;
if (index == n)
{
if (modulo == 0 )
{
return 1 ;
}
return 0 ;
}
if (dp[index][modulo] != - 1 )
{
return dp[index][modulo];
}
int placeAdd = isPossible(n, index + 1 ,
modulo + arr[index], M, arr, dp);
int placeMinus = isPossible(n, index + 1 ,
modulo - arr[index], M, arr, dp);
int res = placeAdd;
dp[index][modulo] = res;
return res;
}
public static void main(String[] args)
{
int arr[] = { 1 , 2 , 3 , 4 , 6 };
int n = arr.length;
int M = 4 ;
int dp[][] = new int [n + 1 ][MAX];
for ( int i = 0 ; i < n + 1 ; i++)
{
for ( int j = 0 ; j < MAX; j++)
{
dp[i][j] = - 1 ;
}
}
boolean res;
if (isPossible(n, 1 , arr[ 0 ], M, arr, dp) == 1 )
{
res = true ;
}
else
{
res = false ;
}
System.out.println(res ? "True" : "False" );
}
}
|
Python3
MAX = 100
def isPossible(n, index, modulo,
M, arr, dp):
modulo = ((modulo % M) + M) % M
if (index = = n):
if (modulo = = 0 ):
return 1
return 0
if (dp[index][modulo] ! = - 1 ):
return dp[index][modulo]
placeAdd = isPossible(n, index + 1 , modulo +
arr[index], M, arr, dp)
placeMinus = isPossible(n, index + 1 , modulo -
arr[index], M, arr, dp)
res = bool (placeAdd or placeMinus)
dp[index][modulo] = res
return res
arr = [ 1 , 2 , 3 , 4 , 6 ]
n = len (arr)
M = 4
dp = [[ - 1 ] * (n + 1 )] * MAX
res = isPossible(n, 1 , arr[ 0 ],
M, arr, dp)
if (res = = True ):
print ( "True" )
else :
print ( "False" )
|
C#
using System;
class GFG
{
static int MAX = 100;
static int isPossible( int n, int index, int modulo,
int M, int []arr, int [,]dp)
{
modulo = ((modulo % M) + M) % M;
if (index == n)
{
if (modulo == 0)
{
return 1;
}
return 0;
}
if (dp[index, modulo] != -1)
{
return dp[index, modulo];
}
int placeAdd = isPossible(n, index + 1,
modulo + arr[index], M, arr, dp);
int placeMinus = isPossible(n, index + 1,
modulo - arr[index], M, arr, dp);
int res = placeAdd;
dp[index, modulo] = res;
return res;
}
public static void Main()
{
int []arr = {1, 2, 3, 4, 6};
int n = arr.Length;
int M = 4;
int [,]dp = new int [n + 1,MAX];
for ( int i = 0; i < n + 1; i++)
{
for ( int j = 0; j < MAX; j++)
{
dp[i, j] = -1;
}
}
bool res;
if (isPossible(n, 1, arr[0], M, arr, dp) == 1)
{
res = true ;
}
else
{
res = false ;
}
Console.WriteLine(res ? "True" : "False" );
}
}
|
Javascript
<script>
const MAX = 100;
function isPossible(n, index, modulo, M, arr, dp)
{
modulo = ((modulo % M) + M) % M;
if (index == n)
{
if (modulo == 0)
{
return 1;
}
return 0;
}
if (dp[index][modulo] != -1)
{
return dp[index][modulo];
}
var placeAdd = isPossible(n, index + 1,
modulo + arr[index],
M, arr, dp);
var placeMinus = isPossible(n, index + 1,
modulo - arr[index],
M, arr, dp);
var res = placeAdd;
dp[index][modulo] = res;
return res;
}
var arr = [ 1, 2, 3, 4, 6 ];
var n = arr.length;
var M = 4;
var dp = Array(n + 1);
for (i = 0; i < n + 1; i++)
{
dp[i] = Array(MAX).fill(-1);
}
var res;
if (isPossible(n, 1, arr[0], M, arr, dp) == 1)
{
res = true ;
}
else
{
res = false ;
}
document.write(res ? "True" : "False" );
</script>
|
Time Complexity: O(N*M).
Auxiliary Space: O(N * MAX), here MAX = 100
Efficient Approach: Follow the steps below in order to solve the problem:
- Evaluate Modulo of all the array element with respect to the given number and store it in the new array, lets say ModArray[].
- Evaluate the sum of the ModArray and store it in sum and check if the sum%M==0 then the output is “true” and return.
- If the sum is odd there will be no case that the following can evaluate to be the number which is divisible by M. Print “False” and return.
- Check if the sum is even then divided it by 2 this is because we have previously summed them and now the task is to delete it so it’s needed to delete it twice hence the number should be even.
- Remove the first element from the ModArray since it is not possible to place minus on the first element.
- Now the solution is converted into the problem where we want to evaluate that whether there exists a solution so that the sum of the elements of a ModArray is equal to the sum or not.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void func( int n, int m, int A[])
{
vector< int > ModArray(n);
int sum = 0;
for ( int i = 0; i < n; i++) {
ModArray[i] = A[i] % m;
sum += ModArray[i];
}
sum = sum % m;
if (sum % m == 0) {
cout << "True" ;
return ;
}
if (sum % 2 != 0) {
cout << "False" ;
}
else {
ModArray.erase(ModArray.begin());
int i = 0;
int j = ModArray.size() - 1;
sort(ModArray.begin(), ModArray.end());
sum = sum / 2;
int i1, i2;
while (i <= j) {
int s = ModArray[i] + ModArray[j];
if (s == sum) {
i1 = i;
i2 = j;
cout << "True" ;
break ;
}
else if (s > sum)
j--;
else
i++;
}
}
}
int main()
{
int m = 2;
int a[] = { 1, 3, 9 };
int n = sizeof a / sizeof a[0];
func(n, m, a);
}
|
Java
import java.util.*;
class GFG{
static void func( int n, int m, int []A)
{
Vector<Integer> ModArray = new Vector<>();
for ( int i = 0 ; i < n; i++)
ModArray.add( 0 );
int sum = 0 ;
for ( int i = 0 ; i < n; i++)
{
ModArray.set(i, A[i] % m);
sum += (( int )ModArray.get(i));
}
sum = sum % m;
if (sum % m == 0 )
{
System.out.println( "True" );
return ;
}
if (sum % 2 != 0 )
{
System.out.println( "False" );
}
else
{
ModArray.remove( 0 );
int i = 0 ;
int j = ModArray.size() - 1 ;
Collections.sort(ModArray);
sum = sum / 2 ;
int i1, i2;
while (i <= j)
{
int s = ( int )ModArray.get(i) +
( int )ModArray.get(j);
if (s == sum)
{
i1 = i;
i2 = j;
System.out.println( "True" );
break ;
}
else if (s > sum)
j--;
else
i++;
}
}
}
public static void main(String args[])
{
int m = 2 ;
int []a = { 1 , 3 , 9 };
int n = a.length;
func(n, m, a);
}
}
|
Python3
def func(n, m, A):
ModArray = [ 0 ] * n
Sum = 0
for i in range (n):
ModArray[i] = A[i] % m
Sum + = ModArray[i]
Sum = Sum % m
if ( Sum % m = = 0 ) :
print ( "True" )
return
if ( Sum % 2 ! = 0 ) :
print ( "False" )
else :
ModArray.pop( 0 )
i = 0
j = len (ModArray) - 1
ModArray.sort()
Sum = Sum / / 2
while (i < = j) :
s = ModArray[i] + ModArray[j]
if (s = = Sum ) :
i1 = i
i2 = j
print ( "True" )
break
elif (s > Sum ):
j - = 1
else :
i + = 1
m = 2
a = [ 1 , 3 , 9 ]
n = len (a)
func(n, m, a)
|
C#
using System.Collections.Generic;
using System;
class GFG{
static void func( int n, int m, int []A)
{
List< int > ModArray = new List< int >();
for ( int i = 0; i < n; i++)
ModArray.Add(0);
int sum = 0;
for ( int i = 0; i < n; i++)
{
ModArray[i] = (A[i] % m);
sum += (( int )ModArray[i]);
}
sum = sum % m;
if (sum % m == 0)
{
Console.WriteLine( "True" );
return ;
}
if (sum % 2 != 0)
{
Console.WriteLine( "False" );
}
else
{
ModArray.Remove(0);
int i = 0;
int j = ModArray.Count - 1;
ModArray.Sort();
sum = sum / 2;
int i1, i2;
while (i <= j)
{
int s = ( int )ModArray[i] +
( int )ModArray[j];
if (s == sum)
{
i1 = i;
i2 = j;
Console.WriteLine( "True" );
break ;
}
else if (s > sum)
j--;
else
i++;
}
}
}
public static void Main()
{
int m = 2;
int []a = { 1, 3, 9 };
int n = a.Length;
func(n, m, a);
}
}
|
Javascript
<script>
function func(n, m, A)
{
let ModArray = [];
for (let i = 0; i < n; i++)
ModArray.push(0);
let sum = 0;
for (let i = 0; i < n; i++)
{
ModArray[i] = A[i] % m;
sum += ModArray[i];
}
sum = sum % m;
if (sum % m == 0)
{
document.write( "True" );
return ;
}
if (sum % 2 != 0)
{
document.write( "False" );
}
else
{
ModArray.shift();
let i = 0;
let j = ModArray.length - 1;
ModArray.sort( function (a, b){ return a - b});
sum = parseInt(sum / 2, 10);
let i1, i2;
while (i <= j)
{
let s = ModArray[i] + ModArray[j];
if (s == sum)
{
i1 = i;
i2 = j;
document.write( "True" );
break ;
}
else if (s > sum)
j--;
else
i++;
}
}
}
let m = 2;
let a = [ 1, 3, 9 ];
let n = a.length;
func(n, m, a);
</script>
|
Time Complexity: O(n * log n)
Auxiliary Space: O(n)
Similar Reads
Check if a number is divisible by 41 or not
Given a number, the task is to quickly check if the number is divisible by 41 or not. Examples: Input : x = 123 Output : Yes Input : 104413920565933 Output : YES A solution to the problem is to extract the last digit and subtract 4 times of the last digit from the remaining number and repeat this pr
6 min read
Check if a number is divisible by 47 or not
Given a number N, the task is to check whether the number is divisible by 47 or not. Examples: Input: N = 1645 Output: yes Explanation: 47 * 35 = 1645Input: N = 4606 Output: yes Explanation: 47 * 98 = 4606 Approach: The divisibility test of 47 is: Extract the last digit.Subtract 14 * last digit from
6 min read
Check if a number is divisible by 31 or not
Given a number N, the task is to check whether the number is divisible by 31 or not. Examples: Input: N = 1922 Output: Yes Explanation: 31 * 62 = 1922Input: N = 2722400 Output: No Approach: The divisibility test of 31 is: Extract the last digit.Subtract 3 * last digit from the remaining number obtai
5 min read
Check if any large number is divisible by 17 or not
Given a number, the task is to quickly check if the number is divisible by 17 or not. Example: Input : x = 34Output : YesInput : x = 47Output : NoA solution to the problem is to extract the last digit and subtract 5 times of the last digit from the remaining number and repeat this process until a tw
10 min read
Check if any large number is divisible by 19 or not
Given a number, the task is to quickly check if the number is divisible by 19 or not. Examples: Input : x = 38Output : YesInput : x = 47Output : NoA solution to the problem is to extract the last digit and add 2 times of last digit to remaining number and repeat this process until a two digit number
9 min read
Check If Array Pair Sums Divisible by k
Given an array of integers and a number k, write a function that returns true if the given array can be divided into pairs such that the sum of every pair is divisible by k. Examples: Input: arr[] = [9, 7, 5, 3], k = 6 Output: True We can divide the array into (9, 3) and (7, 5). Sum of both of these
15 min read
Check if a large number is divisible by 20
Given a number, the task is to check if number is divisible by 20. The input number may be large and it may not be possible to store long long int and it may be very large number then we use the string.Examples: Input : 7575680 Output : Yes Input : 987985865687690 Output : No A number is divisible b
6 min read
Check if a large number is divisible by 5 or not
Given a number, the task is to check if number is divisible by 5. The input number may be large and it may not be possible to store even if we use long long int. Examples: Input : n = 56945255 Output : Yes Input : n = 1234567589333150 Output : Yes Input : n = 3635883959606670431112222 Output : NoRec
4 min read
Check if a large number is divisible by 9 or not
Given a large number as a string s, determine if it is divisible by 9.Note: The number might be so large that it can't be stored in standard data types like long long. Examples: Input : s = "69354"Output: YesExplanation: 69354 is divisible by 9.Input: s = "234567876799333"Output: NoExplanation: 2345
3 min read
Check if a large number is divisible by 8 or not
Given a number, the task is to check if a number is divisible by 8 or not. The input number may be large and it may not be possible to store even if we use long long int.Examples: Input : n = 1128Output : YesInput : n = 1124Output : NoInput : n = 363588395960667043875487Output : NoSince input number
13 min read