Check whether a large number represented as array is divisible by Y
Last Updated :
04 Aug, 2022
Given a large integer X represented as an array arr[] where each arr[i] stores a digit in X. The task is to check whether the number represented by the array is divisible by given integer Y.
Examples:
Input: arr[] = {1, 2, 1, 5, 6}, Y = 4
Output: Yes
12156 / 4 = 3039
Input: arr[] = {1, 1, 1, 1, 1, 1, 1, 1, 1}, Y = 14
Output: No
Approach: Start traversing the digits of the given number from the left and take the largest number which is smaller than or equal to Y and divide it with Y. If the remainder is something other than 0 then it will be carried to the next possible number formed from the remaining digits just like in the long division. After the complete number is processed, if the remainder is still something other than 0 then the represented number is not divisible by Y else it is.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
bool isDivisible( int * arr, int n, int y)
{
int d = 0, i = 0;
while (i < n) {
while (d < y && i < n)
d = d * 10 + arr[i++];
d = d % y;
}
if (d == 0)
return true ;
return false ;
}
int main()
{
int arr[] = { 1, 2, 1, 5, 6 };
int x = sizeof (arr) / sizeof ( int );
int y = 4;
cout << (isDivisible(arr, x, y) ? "Yes" : "No" );
return 0;
}
|
Java
class GFG
{
static boolean isDivisible( int [] arr, int n, int y)
{
int d = 0 , i = 0 ;
while (i < n)
{
while (d < y && i < n)
d = d * 10 + arr[i++];
d = d % y;
}
if (d == 0 )
return true ;
return false ;
}
public static void main (String[] args)
{
int [] arr = { 1 , 2 , 1 , 5 , 6 };
int x = arr.length;
int y = 4 ;
System.out.println(isDivisible(arr, x, y) ? "Yes" : "No" );
}
}
|
Python3
def isDivisible(arr, n, y):
d, i = 0 , 0
while i < n:
while d < y and i < n:
d = d * 10 + arr[i]
i + = 1
d = d % y
if d = = 0 :
return True
return False
if __name__ = = "__main__" :
arr = [ 1 , 2 , 1 , 5 , 6 ]
x = len (arr)
y = 4
if (isDivisible(arr, x, y)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG
{
static bool isDivisible( int [] arr, int n, int y)
{
int d = 0, i = 0;
while (i < n)
{
while (d < y && i < n)
d = d * 10 + arr[i++];
d = d % y;
}
if (d == 0)
return true ;
return false ;
}
public static void Main ()
{
int [] arr = { 1, 2, 1, 5, 6 };
int x = arr.Length;
int y = 4;
Console.WriteLine(isDivisible(arr, x, y) ? "Yes" : "No" );
}
}
|
Javascript
<script>
function isDivisible(vararr , n , y)
{
var d = 0, i = 0;
while (i < n)
{
while (d < y && i < n)
d = d * 10 + arr[i++];
d = d % y;
}
if (d == 0)
return true ;
return false ;
}
var arr = [ 1, 2, 1, 5, 6 ];
var x = arr.length;
var y = 4;
document.write(isDivisible(arr, x, y) ? "Yes" : "No" );
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...