Given a large number, check if a subsequence of digits is divisible by 8
Last Updated :
21 Jul, 2022
Given a number of at most 100 digits. We have to check if it is possible, after removing certain digits, to obtain a number of at least one digit which is divisible by 8. We are forbidden to rearrange the digits.
Examples :
Input : 1787075866
Output : Yes
There exist more one or more subsequences
divisible by 8. Example subsequences are
176, 16 and 8.
Input : 6673177113
Output : No
No subsequence is divisible by 8.
Input : 3144
Output : Yes
The subsequence 344 is divisible by 8.
Property of the divisibility by eight: number can be divided by eight if and only if its last three digits form a number that can be divided by eight. Thus, it is enough to test only numbers that can be obtained from the original one by crossing out and that contain at most three digits i.e we check all one-digit, two digits, and three-digit number combinations.
Method 1 (Brute Force):
We apply the brute force approach. We permute all possible single-digit, double-digit, and triple-digit combinations using an iterative ladder. If we encounter a single-digit number divisible by 8 or a double-digit number combination divisible by 8 or a triple-digit number combination divisible by 8, then that will be the solution to our problem.
C++
#include <bits/stdc++.h>
using namespace std;
bool isSubSeqDivisible(string str)
{
int l = str.length();
int arr[l];
for ( int i = 0; i < l; i++)
arr[i] = str[i] - '0' ;
for ( int i = 0; i < l; i++) {
for ( int j = i; j < l; j++) {
for ( int k = j; k < l; k++) {
if (arr[i] % 8 == 0)
return true ;
else if ((arr[i] * 10 + arr[j]) % 8 == 0 && i != j)
return true ;
else if ((arr[i] * 100 + arr[j] * 10 + arr[k]) % 8 == 0 && i != j && j != k && i != k)
return true ;
}
}
}
return false ;
}
int main()
{
string str = "3144" ;
if (isSubSeqDivisible(str))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
import java.io.*;
class GFG {
static boolean isSubSeqDivisible(String str)
{
int i, j, k, l = str.length();
int arr[] = new int [l];
for (i = 0 ; i < l; i++)
arr[i] = str.charAt(i) - '0' ;
for (i = 0 ; i < l; i++) {
for (j = i; j < l; j++) {
for (k = j; k < l; k++) {
if (arr[i] % 8 == 0 )
return true ;
else if ((arr[i] * 10 + arr[j]) % 8 == 0 && i != j)
return true ;
else if ((arr[i] * 100 + arr[j] * 10 + arr[k]) % 8 == 0
&& i != j && j != k && i != k)
return true ;
}
}
}
return false ;
}
public static void main(String args[])
{
String str = "3144" ;
if (isSubSeqDivisible(str))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def isSubSeqDivisible(st) :
l = len (st)
arr = [ int (ch) for ch in st]
for i in range ( 0 , l) :
for j in range (i, l) :
for k in range (j, l) :
if (arr[i] % 8 = = 0 ) :
return True
elif ((arr[i] * 10 + arr[j]) % 8 = = 0 and i ! = j) :
return True
elif ((arr[i] * 100 + arr[j] * 10 + arr[k]) % 8 = = 0 and i ! = j and j ! = k and i ! = k) :
return True
return False
st = "3144"
if (isSubSeqDivisible(st)) :
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG {
static bool isSubSeqDivisible( string str)
{
int i, j, k, l = str.Length;
int [] arr = new int [l];
for (i = 0; i < n; i++)
arr[i] = str[i] - '0' ;
for (i = 0; i < l; i++) {
for (j = i; j < l; j++) {
for (k = j; k < l; k++) {
if (arr[i] % 8 == 0)
return true ;
else if ((arr[i] * 10 + arr[j])
% 8
== 0
&& i != j)
return true ;
else if ((arr[i] * 100 + arr[j] * 10 + arr[k]) % 8 == 0
&& i != j && j != k
&& i != k)
return true ;
}
}
}
return false ;
}
public static void Main()
{
string str = "3144" ;
if (isSubSeqDivisible(str))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
<script>
function isSubSeqDivisible(str)
{
let i, j, k, l = str.length;
let arr = [];
for (i = 0; i < l; i++)
arr[i] = str[i] - '0' ;
for (i = 0; i < l; i++)
{
for (j = i; j < l; j++)
{
for (k = j; k < l; k++)
{
if (arr[i] % 8 == 0)
return true ;
else if ((arr[i] * 10 + arr[j]) %
8 == 0 && i != j)
return true ;
else if ((arr[i] * 100 + arr[j] * 10 +
arr[k]) % 8 == 0 && i != j &&
j != k && i != k)
return true ;
}
}
}
return false ;
}
let str = "3144" ;
if (isSubSeqDivisible(str))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
PHP
<?php
function isSubSeqDivisible( $str )
{
$l = strlen ( $str );
$arr = [];
for ( $i = 0; $i < $l ; $i ++)
$arr [ $i ] = $str [ $i ] - '0' ;
for ( $i = 0; $i < $l ; $i ++)
{
for ( $j = $i ; $j < $l ; $j ++)
{
for ( $k = $j ; $k < $l ; $k ++)
{
if ( $arr [ $i ] % 8 == 0)
return true;
else if (( $arr [ $i ] * 10 + $arr [ $j ]) %
8 == 0 && $i != $j )
return true;
else if (( $arr [ $i ] * 100 + $arr [ $j ] * 10 +
$arr [ $k ]) % 8 == 0 && $i != $j &&
$j != $k && $i != $k )
return true;
}
}
}
return false;
}
$str = "3144" ;
if (isSubSeqDivisible( $str ))
echo ( "Yes" );
else
echo ( "No" );
?>
|
Time Complexity: O(N3), as we are using nested loops for traversing N3 times. Where N is the length of the string.
Auxiliary Space: O(N), as we are using extra space for the array. Where N is the length of the string.
Method 2 (Dynamic Programming):
Though we have only 100-digit numbers, for longer examples larger than that, our program might exceed the given time limit.
Thus, we optimize our code by using a dynamic programming approach.
Let

Be the ith digit of the sample. We generate a matrix dp[i][j], 1<=i<=n and 0<=j<8. The value of dp is true if we can cross out some digits from the prefix of length i such that the remaining number gives j modulo eight, and false otherwise. For a broad understanding of the concept, if at an index, we find element modulo 8 for that index we put the value of
![Rendered by QuickLaTeX.com dp[i][a_{i}mod8] = 1](https://www.geeksforgeeks.org/wp-content/ql-cache/quicklatex.com-0d0cbdebd5ded8b36f4ff7260c364d66_l3.png)
For all other numbers, we build on a simple concept that either addition of that digit will contribute information of a number divisible by 8, or it shall be left out.
Note: We also have to keep it in mind that we cannot change the order
Now,
![Rendered by QuickLaTeX.com dp[i][(j*10+a_{i}) mod 8]=max(dp[i][(j*10+a_{i}) mod 8], dp[i-1][j])](https://www.geeksforgeeks.org/wp-content/ql-cache/quicklatex.com-cbbf6ac3393be52efbcc312f2d0cc3f1_l3.png)
if we add the current digit to the previous result.
![Rendered by QuickLaTeX.com dp[i][(j*10) mod 8]=max(dp[i][(j*10) mod 8], dp[i-1][j])](https://www.geeksforgeeks.org/wp-content/ql-cache/quicklatex.com-421ba2bb296723ea958d120cdd98a167_l3.png)
if we exclude the current digit in our formation.
Now, if such a number shall exist, we will get a “true” for any i in dp[i][0]
C++
#include <bits/stdc++.h>
using namespace std;
bool isSubSeqDivisible(string str)
{
int n = str.length();
int dp[n + 1][10];
memset (dp, 0, sizeof (dp));
int arr[n + 1];
for ( int i = 1; i <= n; i++)
arr[i] = str[i - 1] - '0' ;
for ( int i = 1; i <= n; i++) {
dp[i][arr[i] % 8] = 1;
for ( int j = 0; j < 8; j++) {
if (dp[i - 1][j] > dp[i][(j * 10 + arr[i]) % 8])
dp[i][(j * 10 + arr[i]) % 8] = dp[i - 1][j];
if (dp[i - 1][j] > dp[i][j])
dp[i][j] = dp[i - 1][j];
}
}
for ( int i = 1; i <= n; i++) {
if (dp[i][0] == 1)
return true ;
}
return false ;
}
int main()
{
string str = "3144" ;
if (isSubSeqDivisible(str))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static boolean isSubSeqDivisible(String str)
{
int n = str.length();
int dp[][] = new int [n + 1 ][ 10 ];
int arr[] = new int [n + 1 ];
for ( int i = 1 ; i <= n; i++)
arr[i] = ( int )(str.charAt(i - 1 ) - '0' );
for ( int i = 1 ; i <= n; i++) {
dp[i][arr[i] % 8 ] = 1 ;
for ( int j = 0 ; j < 8 ; j++) {
if (dp[i - 1 ][j] > dp[i][(j * 10
+ arr[i])
% 8 ])
dp[i][(j * 10 + arr[i]) % 8 ]
= dp[i - 1 ][j];
if (dp[i - 1 ][j] > dp[i][j])
dp[i][j] = dp[i - 1 ][j];
}
}
for ( int i = 1 ; i <= n; i++) {
if (dp[i][ 0 ] == 1 )
return true ;
}
return false ;
}
public static void main(String args[])
{
String str = "3144" ;
if (isSubSeqDivisible(str))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def isSubSeqDivisible( str ):
n = len ( str )
dp = [[ 0 for i in range ( 10 )]
for i in range (n + 1 )]
arr = [ 0 for i in range (n + 1 )]
for i in range ( 1 , n + 1 ):
arr[i] = int ( str [i - 1 ]);
for i in range ( 1 , n + 1 ):
dp[i][arr[i] % 8 ] = 1 ;
for j in range ( 8 ):
if (dp[i - 1 ][j] > dp[i][(j * 10 + arr[i]) % 8 ]):
dp[i][(j * 10 + arr[i]) % 8 ] = dp[i - 1 ][j]
if (dp[i - 1 ][j] > dp[i][j]):
dp[i][j] = dp[i - 1 ][j]
for i in range ( 1 , n + 1 ):
if (dp[i][ 0 ] = = 1 ):
return True
return False
str = "3144"
if (isSubSeqDivisible( str )):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG {
static bool isSubSeqDivisible(String str)
{
int n = str.Length;
int [, ] dp = new int [n + 1, 10];
int [] arr = new int [n + 1];
for ( int i = 1; i <= n; i++)
arr[i] = ( int )(str[i - 1] - '0' );
for ( int i = 1; i <= n; i++) {
dp[i, arr[i] % 8] = 1;
for ( int j = 0; j < 8; j++) {
if (dp[i - 1, j] > dp[i, (j * 10
+ arr[i])
% 8])
dp[i, (j * 10 + arr[i]) % 8]
= dp[i - 1, j];
if (dp[i - 1, j] > dp[i, j])
dp[i, j] = dp[i - 1, j];
}
}
for ( int i = 1; i <= n; i++) {
if (dp[i, 0] == 1)
return true ;
}
return false ;
}
public static void Main()
{
string str = "3144" ;
if (isSubSeqDivisible(str))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
PHP
<?php
function isSubSeqDivisible( $str )
{
$n = strlen ( $str );
$dp = array_fill (0, $n + 1,
array_fill (0, 10, NULL));
$arr = array_fill (0, ( $n + 1), NULL);
for ( $i = 1; $i <= $n ; $i ++)
$arr [ $i ] = $str [ $i - 1] - '0' ;
for ( $i = 1; $i <= $n ; $i ++)
{
$dp [ $i ][ $arr [ $i ] % 8] = 1;
for ( $j = 0; $j < 8; $j ++)
{
if ( $dp [ $i - 1][ $j ] > $dp [ $i ][( $j * 10 +
$arr [ $i ]) % 8])
$dp [ $i ][( $j * 10 +
$arr [ $i ]) % 8] = $dp [ $i - 1][ $j ];
if ( $dp [ $i - 1][ $j ] > $dp [ $i ][ $j ])
$dp [ $i ][ $j ] = $dp [ $i - 1][ $j ];
}
}
for ( $i = 1; $i <= $n ; $i ++)
{
if ( $dp [ $i ][0] == 1)
return true;
}
return false;
}
$str = "3144" ;
if (isSubSeqDivisible( $str ))
echo "Yes" ;
else
echo "No" ;
?>
|
Javascript
<script>
function isSubSeqDivisible(str)
{
let n = str.length;
let dp = new Array(n + 1);
for (let i = 0; i < 10; i++)
{
dp[i] = new Array(10);
for (let j = 0; j < 10; j++)
{
dp[i][j] = 0;
}
}
let arr = new Array(n + 1);
for (let i = 1; i <= n; i++)
arr[i] = (str[i - 1].charCodeAt() - '0' .charCodeAt());
for (let i = 1; i <= n; i++) {
dp[i][arr[i] % 8] = 1;
for (let j = 0; j < 8; j++) {
if (dp[i - 1][j] > dp[i][(j * 10 + arr[i]) % 8])
dp[i][(j * 10 + arr[i]) % 8] = dp[i - 1][j];
if (dp[i - 1][j] > dp[i][j])
dp[i][j] = dp[i - 1][j];
}
}
for (let i = 1; i <= n; i++) {
if (dp[i][0] == 1)
return true ;
}
return false ;
}
let str = "3144" ;
if (isSubSeqDivisible(str))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity: O(n), as using the dynamic approach, our time complexity cuts down to O(8*n) as we are using linear traversal. Where 8 is from which the number should be divisible and n is the length of our input.
Auxiliary Space: O(n), as we are using extra space for the dp matrix. Where N is the length of our input.
Method 3
For this problem, we simply need to check if there exists a two-digit subsequence divisible by 8 (divisibility test for 8)
We first find all the 2 digit numbers divisible by 8 and map the tens place digit with unit place digit
i.e :- 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96
Ignore 48 as 8 is always divisible by 8 similarly 80 and 88 have 8 in them which make such subsequence always divisible by 8
So we map 1 to 6, 2 to 4, 3 to 2, and so on using map i.e stl map in C++.
After building the map we traverse the string from the last index and check if the mapped value of the present index number is visited or not hence we need a visited array for this which will store true if the number is visited, else false
eg:- 3769
first char from the last index is 9 so we check if 6 is visited (i.e 96 is subsequence or not), we mark 9 in visited array
next char is 6 so we check is 4 visited (i.e 64), we mark 6 in the visited array
next char is 7 so we check is 2 visited (i.e 72), we mark 7 in the visited array
next char is 3 so we check is 6 visited (i.e 36), yes 6 is marked hence we print Yes.
C++
#include<bits/stdc++.h>
using namespace std;
int main(){
string str = "129365" ;
map< int , int > mp;
int no = 8;
while (no < 100){
no = no + 8;
mp.insert({(no / 10) % 10, no % 10});
}
vector< bool > visited(10, false );
int i;
for (i = str.length() - 1; i >= 0; i--){
if (str[i] == '8' )
{
cout << "Yes" ;
break ;
}
if (visited[mp[str[i] - '0' ]]){
cout << "Yes" ;
break ;
}
visited[str[i] - '0' ] = true ;
}
if (i == -1)
cout << "No" ;
return 0;
}
|
Java
import java.util.*;
class GFG{
public static void main(String[] args)
{
String str = "129365" ;
HashMap<Integer,
Integer> mp = new HashMap<Integer,
Integer>();
int no = 8 ;
while (no < 100 )
{
no = no + 8 ;
mp.put((no / 10 ) % 10 , no % 10 );
}
boolean [] visited = new boolean [ 10 ];
int i;
for (i = str.length() - 1 ;
i >= 0 ; i--)
{
if (str.charAt(i) == '8' )
{
System.out.print( "Yes" );
break ;
}
if (visited[mp.get(str.charAt(i)- '0' )])
{
System.out.print( "Yes" );
break ;
}
visited[str.charAt(i) - '0' ] = true ;
}
if (i == - 1 )
System.out.print( "No" );
}
}
|
Python3
Str = "129365"
mp = {}
no = 8
while (no < 100 ) :
no = no + 8
mp[(no / / 10 ) % 10 ] = no % 10
visited = [ False ] * 10
for i in range ( len ( Str ) - 1 , - 1 , - 1 ) :
if ( Str [i] = = '8' ) :
print ( "Yes" , end = "")
break
if visited[mp[ ord ( Str [i]) - ord ( '0' )]] :
print ( "Yes" , end = "")
break
visited[ ord ( Str [i]) - ord ( '0' )] = True
if (i = = - 1 ) :
print ( "No" )
|
C#
using System;
using System.Collections.Generic;
class GFG{
public static void Main(String[] args)
{
String str = "129365" ;
Dictionary< int ,
int > mp = new Dictionary< int ,
int >();
int no = 8;
while (no < 100)
{
no = no + 8;
if (mp.ContainsKey((no / 10) % 10))
mp[(no / 10) % 10] = no % 10;
else
mp.Add((no / 10) % 10, no % 10);
}
bool [] visited = new bool [10];
int i;
for (i = str.Length - 1; i >= 0; i--)
{
if (str[i] == '8' )
{
Console.Write( "Yes" );
break ;
}
if (visited[mp[str[i] - '0' ]])
{
Console.Write( "Yes" );
break ;
}
visited[str[i] - '0' ] = true ;
}
if (i == -1)
Console.Write( "No" );
}
}
|
Javascript
<script>
let str = "129365" ;
let mp = new Map();
let no = 8;
while (no < 100)
{
no = no + 8;
mp.set((Math.floor(no / 10)) % 10, no % 10);
}
let visited = new Array(10);
for (let i=0;i<visited.length;i++)
{
visited[i]= false ;
}
let i;
for (i = str.length - 1;
i >= 0; i--)
{
if (str[i] == '8' )
{
document.write( "Yes" );
break ;
}
if (visited[mp.get(str[i].charCodeAt(0)-
'0' .charCodeAt(0))])
{
document.write( "Yes" );
break ;
}
visited[str[i].charCodeAt(0) -
'0' .charCodeAt(0)] = true ;
}
if (i == -1)
document.write( "No" );
</script>
|
Time Complexity: O(n), as we are using a loop to traverse n times. Where n is the length of our input.
Auxiliary Space: O(1), as if you take a close look, the visited array will always have 10 fields and the map will always have the same size, hence space complexity will O(1).
Similar Reads
Check if any permutation of a large number is divisible by 8
Given a large number N and the task is to check if any permutation of a large number is divisible by 8. Examples: Input: N = 31462708 Output: Yes Many of permutation of number N like 34678120, 34278160 are divisible by 8. Input: 75 Output: No A naive approach is to generate all permutations of the n
10 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
Largest K digit number divisible by all numbers in given array
Given an array arr[] of size N and an integer K. The task is to find the largest K digit number divisible by all number of arr[]. Examples: Input: arr[] = {2, 3, 5}, K = 3Output: 990Explanation: 990 is the largest 3 digit number divisible by 2, 3 and 5. Input: arr[] = {91, 93, 95}, K = 3Output: -1Ex
6 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 4 or not
Given a number, the task is to check if a number is divisible by 4 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 = 1124Output : YesInput : n = 1234567589333862Output : NoInput : n = 363588395960667043875487Output : No Usin
12 min read
Program to check if a number is divisible by any of its digits
Given an integer N where [Tex]1 \leq n \leq 10^{18} [/Tex]. The task is to check whether the number is not divisible by any of its digit. If the given number N is divisible by any of its digits then print "YES" else print "NO". Examples: Input : N = 5115Output : YESExplanation: 5115 is divisible by
10 min read
Check if a large number is divisible by 6 or not
Given a number, the task is to check if a number is divisible by 6 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 = 2112Output: YesInput : n = 1124Output : NoInput : n = 363588395960667043875487Output : No[GFGTABS] C++ #inc
7 min read
Check if a large number is divisible by 3 or not
Given a number, the task is that we divide number by 3. The input number may be large and it may not be possible to store even if we use long long int.Examples: Input : n = 769452Output : YesInput : n = 123456758933312Output : NoInput : n = 3635883959606670431112222Output : YesSince input number may
7 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
Program to check if a number is divisible by sum of its digits
Given an integer N, the task is to check whether the number is divisible by the sum of its digits or not. If divisible, then print âYESâ else print âNOâ. Examples: Input: N = 12 Output: YES Explanation: As sum of digits of 12 = 1 + 2 = 3 and 12 is divisible by 3 So the output is YES Input: N = 123 O
7 min read