Count of numbers from the range [L, R] which contains at least one digit that divides K
Last Updated :
09 Jun, 2022
Given three positive integers L, R and K.The task is to find the count of all the numbers from the range [L, R] that contains at least one digit which divides the number K.
Examples:
Input: L = 5, R = 11, K = 10
Output: 3
5, 10 and 11 are only such numbers.
Input: L = 32, R = 38, K = 13
Output: 0
Approach: Initialise count = 0 and for every element in the range [L, R], check if it contains at least one digit that divides K. If yes then increment the count.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool digitDividesK( int num, int k)
{
while (num) {
int d = num % 10;
if (d != 0 and k % d == 0)
return true ;
num = num / 10;
}
return false ;
}
int findCount( int l, int r, int k)
{
int count = 0;
for ( int i = l; i <= r; i++) {
if (digitDividesK(i, k))
count++;
}
return count;
}
int main()
{
int l = 20, r = 35;
int k = 45;
cout << findCount(l, r, k);
return 0;
}
|
Java
class GFG
{
static boolean digitDividesK( int num, int k)
{
while (num != 0 )
{
int d = num % 10 ;
if (d != 0 && k % d == 0 )
return true ;
num = num / 10 ;
}
return false ;
}
static int findCount( int l, int r, int k)
{
int count = 0 ;
for ( int i = l; i <= r; i++)
{
if (digitDividesK(i, k))
count++;
}
return count;
}
public static void main(String []args)
{
int l = 20 , r = 35 ;
int k = 45 ;
System.out.println(findCount(l, r, k));
}
}
|
Python3
def digitDividesK(num, k):
while (num):
d = num % 10
if (d ! = 0 and k % d = = 0 ):
return True
num = num / / 10
return False
def findCount(l, r, k):
count = 0
for i in range (l, r + 1 ):
if (digitDividesK(i, k)):
count + = 1
return count
l = 20
r = 35
k = 45
print (findCount(l, r, k))
|
C#
using System;
class GFG
{
static bool digitDividesK( int num, int k)
{
while (num != 0)
{
int d = num % 10;
if (d != 0 && k % d == 0)
return true ;
num = num / 10;
}
return false ;
}
static int findCount( int l, int r, int k)
{
int count = 0;
for ( int i = l; i <= r; i++)
{
if (digitDividesK(i, k))
count++;
}
return count;
}
public static void Main()
{
int l = 20, r = 35;
int k = 45;
Console.WriteLine(findCount(l, r, k));
}
}
|
Javascript
<script>
function digitDividesK(num, k)
{
while (num)
{
let d = num % 10;
if (d != 0 && k % d == 0)
return true ;
num = parseInt(num / 10);
}
return false ;
}
function findCount(l, r, k)
{
let count = 0;
for (let i = l; i <= r; i++)
{
if (digitDividesK(i, k))
count++;
}
return count;
}
let l = 20, r = 35;
let k = 45;
document.write(findCount(l, r, k));
</script>
|
Time Complexity: O((r-l)*(log10(num)))
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...