Given a positive integer n. The task is to find count of digits of number which evenly divides the number n.
Examples:
Input : n = 12
Output : 2
1 and 2 divide 12.
Input : n = 1012
Output : 3
1, 1 and 2 divide 1012.
The idea is to find each digit of the number n by modulus 10 and then check whether it divides n or not. Accordingly, increment the counter. Notice that the digit can be 0, so take care of that case.
Below is implementation of this approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countDigit( int n)
{
int temp = n, count = 0;
while (temp != 0) {
int d = temp % 10;
temp /= 10;
if (d > 0 && n % d == 0)
count++;
}
return count;
}
int main()
{
int n = 1012;
cout << countDigit(n) << endl;
return 0;
}
|
Java
class Test {
static int countDigit( int n)
{
int temp = n, count = 0 ;
while (temp != 0 ) {
int d = temp % 10 ;
temp /= 10 ;
if (d > 0 && n % d == 0 )
count++;
}
return count;
}
public static void main(String args[])
{
int n = 1012 ;
System.out.println(countDigit(n));
}
}
|
Python3
def countDigit (n):
temp = n
count = 0
while temp ! = 0 :
d = temp % 10
temp / / = 10
if d > 0 and n % d = = 0 :
count + = 1
return count
n = 1012
print (countDigit(n))
|
C#
using System;
class GFG {
static int countDigit( int n)
{
int temp = n, count = 0;
while (temp != 0) {
int d = temp % 10;
temp /= 10;
if (d > 0 && n % d == 0)
count++;
}
return count;
}
public static void Main()
{
int n = 1012;
Console.Write(countDigit(n));
}
}
|
PHP
<?php
function countDigit( $n )
{
$temp = $n ;
$count = 0;
while ( $temp != 0)
{
$d = $temp % 10;
$temp /= 10;
if ( $d > 0 && $n % $d == 0)
$count ++;
}
return $count ;
}
$n = 1012;
echo countDigit( $n ), "\n" ;
?>
|
Javascript
<script>
function countDigit(n)
{
var temp = n, count = 0;
while (temp != 0)
{
var d = temp % 10;
temp /= 10;
if (d > 0 && n % d == 0)
count++;
}
return count;
}
var n = 1012;
document.write(countDigit(n));
</script>
|
Output:
3
Time Complexity: O(d) where d is the number of digits in a number.
Auxiliary Space: O(1)
This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.