Open In App

Count digits in given number N which divide N

Improve
Improve
Like Article
Like
Save
Share
Report

Given a number N which may be 10^5 digits long, the task is to count all the digits in N which divide N. Divisibility by 0 is not allowed. If any digit in N which is repeated divides N, then all repetitions of that digit should be counted i. e., N = 122324, here 2 divides N and it appears 3 times. So count for digit 2 will be 3.
Examples: 
 

Input  : N = "35"
Output : 1
There are two digits in N and 1 of them
(5)divides it.
Input : N = "122324"
Output : 5
N is divisible by 1, 2 and 4

 

Recommended Practice

How to check divisibility of a digit for large N stored as string? 
The idea is to use distributive property of mod operation. 
(x+y)%a = ((x%a) + (y%a)) % a.
 

// This function returns true if digit divides N, 
// else false
bool divisible(string N, int digit)
{
int ans = 0;
for (int i = 0; i < N.length(); i++)
{
// (N[i]-'0') gives the digit value and
// form the number
ans = (ans*10 + (N[i]-'0'));
// We use distributive property of mod here.
ans %= digit;
}
return (ans == 0);
}

A simple solution for this problem is to read number in string form and one by one check divisibility by each digit which appears in N. Time complexity for this approach will be O(N2).
An efficient solution for this problem is to use an extra array divide[] of size 10. Since we have only 10 digits so run a loop from 1 to 9 and check divisibility of N with each digit from 1 to 9. If any digit divides N then mark true in divide[] array at digit as index. Now traverse the number string and increment result if divide[i] is true for current digit i. 
 

C++




// C++ program to find number of digits in N that
// divide N.
#include<bits/stdc++.h>
using namespace std;
 
// Utility function to check divisibility by digit
bool divisible(string N, int digit)
{
    int ans = 0;
    for (int i = 0; i < N.length(); i++)
    {
        // (N[i]-'0') gives the digit value and
        // form the number
        ans  = (ans*10 + (N[i]-'0'));
        ans %= digit;
    }
    return (ans == 0);
}
 
// Function to count digits which appears in N and
// divide N
// divide[10]  --> array which tells that particular
//                 digit divides N or not
// count[10]   --> counts frequency of digits which
//                 divide N
int allDigits(string N)
{
    // We initialize all digits of N as not divisible
    // by N.
    bool divide[10] = {false};
    divide[1] = true// 1 divides all numbers
 
    // start checking divisibility of N by digits 2 to 9
    for (int digit=2; digit<=9; digit++)
    {
        // if digit divides N then mark it as true
        if (divisible(N, digit))
            divide[digit] = true;
    }
 
    // Now traverse the number string to find and increment
    // result whenever a digit divides N.
    int result = 0;
    for (int i=0; i<N.length(); i++)
    {
        if (divide[N[i]-'0'] == true)
            result++;
    }
 
    return result;
}
 
// Driver program to run the case
int main()
{
    string N = "122324";
    cout << allDigits(N);
    return 0;
}


Java




// Java program to find number of digits in N that
// divide N.
import java.util.*;
 
class solution
{
 
// Utility function to check divisibility by digit
static boolean divisible(String N, int digit)
{
    int ans = 0;
    for (int i = 0; i < N.length(); i++)
    {
        // (N[i]-'0') gives the digit value and
        // form the number
        ans = (ans*10 + (N.charAt(i)-'0'));
        ans %= digit;
    }
    return (ans == 0);
}
 
// Function to count digits which appears in N and
// divide N
// divide[10] --> array which tells that particular
//                 digit divides N or not
// count[10] --> counts frequency of digits which
//                 divide N
static int allDigits(String N)
{
    // We initialize all digits of N as not divisible
    // by N.
    Boolean[] divide = new Boolean[10];
    Arrays.fill(divide, Boolean.FALSE);
    divide[1] = true; // 1 divides all numbers
 
    // start checking divisibility of N by digits 2 to 9
    for (int digit=2; digit<=9; digit++)
    {
        // if digit divides N then mark it as true
        if (divisible(N, digit))
            divide[digit] = true;
    }
 
    // Now traverse the number string to find and increment
    // result whenever a digit divides N.
    int result = 0;
    for (int i=0; i<N.length(); i++)
    {
        if (divide[N.charAt(i)-'0'] == true)
            result++;
    }
 
    return result;
}
 
// Driver program to run the case
public static void main(String args[])
{
    String N = "122324";
    System.out.println(allDigits(N));
}
 
}
// This code is contributed by Surendra_Gangwar


Python3




# Python3 program to find number of
# digits in N that divide N.
 
# Utility function to check
# divisibility by digit
def divisible(N, digit):
  
    ans = 0;
    for i in range(len(N)):
        # (N[i]-'0') gives the digit
        # value and form the number
        ans = (ans * 10 + (ord(N[i]) - ord('0')));
        ans %= digit;
    return (ans == 0);
 
# Function to count digits which
# appears in N and divide N
# divide[10] --> array which tells
# that particular digit divides N or not
# count[10] --> counts frequency of
#                 digits which divide N
def allDigits(N):
  
    # We initialize all digits of N
    # as not divisible by N.
    divide =[False]*10;
    divide[1] = True; # 1 divides all numbers
 
    # start checking divisibility of
    # N by digits 2 to 9
    for digit in range(2,10):
        # if digit divides N then
        # mark it as true
        if (divisible(N, digit)):
            divide[digit] = True;
 
    # Now traverse the number string to
    # find and increment result whenever
    # a digit divides N.
    result = 0;
    for i in range(len(N)):
      
        if (divide[(ord(N[i]) - ord('0'))] == True):
            result+=1;
 
    return result;
 
# Driver Code
N = "122324";
print(allDigits(N));
 
# This code is contributed by mits


C#




// C# program to find number of digits
// in N that divide N.
using System;
 
class GFG {
     
// Utility function to
// check divisibility by digit
static bool divisible(string N, int digit)
{
    int ans = 0;
    for (int i = 0; i < N.Length; i++)
    {
         
        // (N[i]-'0') gives the digit value and
        // form the number
        ans = (ans * 10 + (N[i] - '0'));
        ans %= digit;
    }
    return (ans == 0);
}
 
// Function to count digits which
// appears in N and divide N
// divide[10] --> array which
// tells that particular
// digit divides N or not
// count[10] --> counts
// frequency of digits which
// divide N
static int allDigits(string N)
{
     
    // We initialize all digits
    // of N as not divisible by N
    bool[] divide = new bool[10];
     
    for (int i = 0; i < divide.Length; i++)
    {
        divide[i] = false;
    }
     
    // 1 divides all numbers
    divide[1] = true;
 
    // start checking divisibility
    // of N by digits 2 to 9
    for (int digit = 2; digit <= 9; digit++)
    {
         
        // if digit divides N
        // then mark it as true
        if (divisible(N, digit))
            divide[digit] = true;
    }
 
    // Now traverse the number
    // string to find and increment
    // result whenever a digit divides N.
    int result = 0;
     
    for (int i = 0; i < N.Length; i++)
    {
        if (divide[N[i] - '0'] == true)
            result++;
    }
 
    return result;
}
 
// Driver Code
public static void Main()
{
    string N = "122324";
    Console.Write(allDigits(N));
}
}
 
// This code is contributed
// by Akanksha Rai(Abby_akku)


Javascript




<script>
 
// JavaScript program to find number of digits
// in N that divide N.
 
// Utility function to
// check divisibility by digit
function divisible(N, digit)
{
    let ans = 0;
    for (let i = 0; i < N.length; i++)
    {
           
        // (N[i]-'0') gives the digit value and
        // form the number
        ans = (ans * 10 + (N[i] - '0'));
        ans %= digit;
    }
    return (ans == 0);
}
   
// Function to count digits which
// appears in N and divide N
// divide[10] --> array which
// tells that particular
// digit divides N or not
// count[10] --> counts
// frequency of digits which
// divide N
function allDigits(N)
{
       
    // We initialize all digits
    // of N as not divisible by N
    let divide = [];
       
    for (let i = 0; i < divide.length; i++)
    {
        divide[i] = false;
    }
       
    // 1 divides all numbers
    divide[1] = true;
   
    // start checking divisibility
    // of N by digits 2 to 9
    for (let digit = 2; digit <= 9; digit++)
    {
           
        // if digit divides N
        // then mark it as true
        if (divisible(N, digit))
            divide[digit] = true;
    }
   
    // Now traverse the number
    // string to find and increment
    // result whenever a digit divides N.
    let result = 0;
       
    for (let i = 0; i < N.length; i++)
    {
        if (divide[N[i] - '0'] == true)
            result++;
    }
   
    return result;
}
     
// Driver Code
    let N = "122324";
    document.write(allDigits(N));
         
// This code is contributed by chinmoy1997pal.
</script>


PHP




<?php
// PHP program to find number of
// digits in N that divide N.
 
// Utility function to check
// divisibility by digit
function divisible($N, $digit)
{
    $ans = 0;
    for ($i = 0; $i < strlen($N); $i++)
    {
        // (N[i]-'0') gives the digit
        // value and form the number
        $ans = ($ans * 10 + (int)($N[$i] - '0'));
        $ans %= $digit;
    }
    return ($ans == 0);
}
 
// Function to count digits which
// appears in N and divide N
// divide[10] --> array which tells
// that particular digit divides N or not
// count[10] --> counts frequency of
//                 digits which divide N
function allDigits($N)
{
    // We initialize all digits of N
    // as not divisible by N.
    $divide = array_fill(0, 10, false);
    $divide[1] = true; // 1 divides all numbers
 
    // start checking divisibility of
    // N by digits 2 to 9
    for ($digit = 2; $digit <= 9; $digit++)
    {
        // if digit divides N then
        // mark it as true
        if (divisible($N, $digit))
            $divide[$digit] = true;
    }
 
    // Now traverse the number string to
    // find and increment result whenever
    // a digit divides N.
    $result = 0;
    for ($i = 0; $i < strlen($N); $i++)
    {
        if ($divide[(int)($N[$i] - '0')] == true)
            $result++;
    }
 
    return $result;
}
 
// Driver Code
$N = "122324";
echo allDigits($N);
 
// This code is contributed by mits
?>


Output : 

5

Time Complexity: O(n) 
Auxiliary space: O(1)
This article is contributed by Shashank Mishra .

Approach#2:Using reursion

In this approach, we will use recursion to count the number of digits that divide N. We will first check if the length of N is 1. If it is, we will check if the digit divides N. If it does, we will return 1, else we will return 0. If the length of N is greater than 1, we will call the function recursively on the first digit of N and add the result to the recursive call on the remaining digits of N.

Algorithm

1. Take the input value of N.
2. Define a recursive function to count the number of digits that divide N.
3. If the length of N is 1, check if the digit divides N. If it does, return 1, else return 0.
4. If the length of N is greater than 1, call the function recursively on the first digit of N and add the result to the recursive call on the remaining digits of N.
5. Return the result of the recursive call.

C++




#include <iostream>
#include <string>
using namespace std;
 
// Helper function to recursively count dividing digits
int helper(string N) {
    if (N.length() == 1) {  // Base case: single digit
        if (N != "0" && N != "1" && stoi(N) % stoi(N) == 0) {
            return 1;
        } else {
            return 0;
        }
    } else // Recursive case: multiple digits
        if (N[0] != '0' && N[0] != '1' && stoi(N) % stoi(string(1, N[0])) == 0) {
            return 1 + helper(N.substr(1));
        } else {
            return helper(N.substr(1));
        }
    }
}
 
int count_dividing_digits(string N)
{
   
    // Call helper function with input string and return result
    return helper(N);
}
 
int main() {
    string N = "122324";
    cout << count_dividing_digits(N) << endl;
    return 0;
}


Java




public class Main {
    // Helper function to recursively count dividing digits
    static int helper(String N) {
        if (N.length() == 1) {  // Base case
            if (!N.equals("0") && !N.equals("1") && Integer.parseInt(N) % Integer.parseInt(N) == 0) {
                return 1;
            } else {
                return 0;
            }
        } else // Recursive case for multiple digits
            if (N.charAt(0) != '0' && N.charAt(0) != '1' && Integer.parseInt(N) % Integer.parseInt(String.valueOf(N.charAt(0))) == 0) {
                return 1 + helper(N.substring(1));
            } else {
                return helper(N.substring(1));
            }
        }
    }
 
    static int countDividingDigits(String N) {
       // Call helper function with input string and return result
        return helper(N);
    }
 
  //Driver Code
    public static void main(String[] args) {
        String N = "122324";
        System.out.println(countDividingDigits(N));
    }
}


Python3




def count_dividing_digits(N):
    def helper(N):
        if len(N) == 1:
            if int(N) != 0 and int(N) != 1 and int(N) % int(N) == 0:
                return 1
            else:
                return 0
        else:
            if int(N[0]) != 0 and int(N[0]) != 1 and int(N) % int(N[0]) == 0:
                return 1 + helper(N[1:])
            else:
                return helper(N[1:])
    return helper(str(N))
 
N = "122324"
print(count_dividing_digits(N))


C#




using System;
 
class Program
{
    // Helper function to recursively count dividing digits
    static int Helper(string N)
    {
        if (N.Length == 1) // Base case: single digit
        {
            if (N != "0" && N != "1" && int.Parse(N) % int.Parse(N) == 0)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }
        else // Recursive case: multiple digits
        {
            if (N[0] != '0' && N[0] != '1' && int.Parse(N) % int.Parse(N[0].ToString()) == 0)
            {
                return 1 + Helper(N.Substring(1));
            }
            else
            {
                return Helper(N.Substring(1));
            }
        }
    }
 
    static int CountDividingDigits(string N)
    {
        // Call helper function with input string and return result
        return Helper(N);
    }
 
    static void Main()
    {
        string N = "122324";
        Console.WriteLine(CountDividingDigits(N));
    }
}


Javascript




// Helper function to recursively count dividing digits
function helper(N) {
    // Base case: single digit
    if (N.length === 1) {
        if (N !== '0' && N !== '1' && parseInt(N) % parseInt(N) === 0) {
            return 1;
        } else {
            return 0;
        }
    } else {
        // Recursive case: multiple digits
        if (N[0] !== '0' && N[0] !== '1' && parseInt(N) % parseInt(N[0]) === 0) {
            return 1 + helper(N.substr(1));
        } else {
            return helper(N.substr(1));
        }
    }
}
 
// Function to count the number of dividing digits in a string
function countDividingDigits(N) {
    // Call the helper function with the input string and return the result
    return helper(N);
}
 
// Main function
function main() {
    const N = "122324";
    console.log(countDividingDigits(N)); // Output: 4
}
 
// Invoke the main function
main();


Output

5













Time complexity: O(n), where n is the number of digits in N. This is because the code iterates through each digit of N exactly once and performs constant time operations on each digit.

Auxiliary Space: O(n), since the recursive function helper() is called n times and each call creates a new stack frame with some constant amount of memory usage. Therefore, the space used by the function scales linearly with the input size.

Approach:

In this approach, we create a vector counts of size 10 to keep track of the number of times each digit 0-9 appears and divides the input string N. We loop through each character in the input string N, convert it to an integer, and check if it is a divisor of N. If so, we increment the count for that digit. Finally, we loop through the counts vector and add up the counts for all digits except 0 (since 0 cannot be a divisor of any number except 0 itself).

Algorithm:

  1. Initialize a vector counts of size 10 with all elements set to zero.
  2. Loop through each character in the input string N.
  3. Convert the character to an integer value.
  4. Check if the integer value is zero. If it is, continue to the next iteration of the loop.
  5. Check if the integer value is a divisor of N. If it is, increment the count of the corresponding digit in the counts vector.
  6. Loop through the counts vector and add up the counts for all digits except 0.
  7. Return the total count.

C++




#include <iostream>
#include <vector>
using namespace std;
 
int allDigits(string N) {
    vector<int> counts(10, 0); // Initialize counts for digits 0-9 to zero
 
    for(char ch : N) {
        int digit = ch - '0'; // Convert char to int
        if(digit == 0) continue; // Ignore zero digits
        if(stoi(N) % digit == 0) counts[digit]++; // Increment count if digit divides N
    }
 
    int result = 0;
    for(int i = 1; i < 10; i++) {
        if(counts[i] > 0) result += counts[i];
    }
    return result;
}
 
int main() {
    string N = "122324";
    cout << allDigits(N) << endl;
    return 0;
}


Java




import java.util.Arrays;
 
public class AllDigits {
    public static int allDigits(String N) {
        int[] counts = new int[10]; // Initialize counts for digits 0-9 to zero
 
        for (char ch : N.toCharArray()) {
            int digit = ch - '0'; // Convert char to int
            if (digit == 0) continue; // Ignore zero digits
            if (Integer.parseInt(N) % digit == 0) counts[digit]++; // Increment count if digit
                                                                   // divides N
        }
 
        int result = 0;
        for (int i = 1; i < 10; i++) {
            if (counts[i] > 0) result += counts[i];
        }
        return result;
    }
 
    public static void main(String[] args) {
        String N = "122324";
        System.out.println(allDigits(N));
    }
}


Python3




def all_digits(N):
    counts = [0] * 10  # Initialize counts for digits 0-9 to zero
 
    for ch in N:
        digit = int(ch)  # Convert char to int
        if digit == 0:
            continue  # Ignore zero digits
        if int(N) % digit == 0:
            counts[digit] += 1  # Increment count if digit divides N
 
    result = 0
    for i in range(1, 10):
        if counts[i] > 0:
            result += counts[i]
    return result
 
N = "122324"
print(all_digits(N))
 
# This code is contributed by Dwaipayan Bandyopadhyay


C#




using System;
using System.Collections.Generic;
 
class Program {
    static int AllDigits(string N)
    {
        // Initialize counts for digits 0-9 to zero
        int[] counts = new int[10];
 
        foreach(char ch in N)
        {
            int digit = ch - '0'; // Convert char to int
            if (digit == 0)
                continue; // Ignore zero digits
            if (int.Parse(N) % digit == 0)
                counts[digit]++; // Increment count if digit
                                 // divides N
        }
 
        int result = 0;
        for (int i = 1; i < 10; i++) {
            if (counts[i] > 0)
                result += counts[i];
        }
        return result;
    }
 
    static void Main()
    {
        string N = "122324";
        Console.WriteLine(AllDigits(N));
    }
}


Javascript




function allDigits(N) {
    const counts = Array(10).fill(0); // Initialize counts for digits 0-9 to zero
 
    for (const ch of N) {
        const digit = parseInt(ch); // Convert char to int
        if (digit === 0) continue; // Ignore zero digits
        if (parseInt(N) % digit === 0) counts[digit]++; // Increment count if digit divides N
    }
 
    let result = 0;
    for (let i = 1; i < 10; i++) {
        if (counts[i] > 0) result += counts[i];
    }
    return result;
}
 
// Main function
const N = "122324";
console.log(allDigits(N));


Output

5














Time complexity : O(N)

Auxiliary space : O(1).



Last Updated : 18 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads