Count digits in given number N which divide N
Last Updated :
18 Dec, 2023
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
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();
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:
- Initialize a vector counts of size 10 with all elements set to zero.
- Loop through each character in the input string N.
- Convert the character to an integer value.
- Check if the integer value is zero. If it is, continue to the next iteration of the loop.
- Check if the integer value is a divisor of N. If it is, increment the count of the corresponding digit in the counts vector.
- Loop through the counts vector and add up the counts for all digits except 0.
- 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));
Time complexity : O(N)
Auxiliary space : O(1).
Similar Reads
Find count of digits in a number that divide the number
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. Recommended PracticeCount DigitsTry It! The idea is to find each digit of the number
4 min read
Count n digit numbers divisible by given number
Given number of digit n and a number, the task is to count all the numbers which are divisible by that number and having n digit. Examples : Input : n = 2, number = 7Output : 13Explanation: There are nine n digit numbers that are divisible by 7. Numbers are 14, 21, 28, 35, 42, 49, .... 91, 98 Input
8 min read
Count of unique digits in a given number N
Given a number N, the task is to count the number of unique digits in the given number. Examples: Input: N = 22342 Output: 2 Explanation:The digits 3 and 4 occurs only once. Hence, the output is 2. Input: N = 99677 Output: 1Explanation:The digit 6 occurs only once. Hence, the output is 1. Naive Appr
6 min read
Find N digits number which is divisible by D
Given N and D . The task is to find an N digit number that is divisible by D ( 2 <= D <= 10). If it is not possible, then print Impossible. Examples: Input : N = 2 and D = 2Output : 20 Input : N = 1 and D = 10Output : Impossible Approach: There are two conditions, D=10 and D not equal to 10. I
5 min read
Count N digits numbers with sum divisible by K
Given two integers N and K, the task is to count all N digits numbers whose sum of digits is divisible by K. Examples: Input: N = 2, K = 7Output: 12Explanation: 2 digits numbers with sum divisible by 7 are: {16, 25, 34, 43, 52, 59, 61, 68, 70, 77, 86, 95}.Therefore, the required output is 12. Input:
15+ min read
Count n digit numbers not having a particular digit
We are given two integers n and d, we need to count all n digit numbers that do not have digit d. Example : Input : n = 2, d = 7 Output : 72 All two digit numbers that don't have 7 as digit are 10, 11, 12, 13, 14, 15, 16, 18, ..... Input : n = 3, d = 9 Output : 648 A simple solution is to traverse t
8 min read
Count of N-digit numbers with all distinct digits
Given an integer N, the task is to find the count of N-digit numbers with all distinct digits.Examples: Input: N = 1 Output: 9 1, 2, 3, 4, 5, 6, 7, 8 and 9 are the 1-digit numbers with all distinct digits.Input: N = 3 Output: 648 Naive Approach: If N > 10 i.e. there will be atleast one digit whic
7 min read
Find numbers with n-divisors in a given range
Given three integers a, b, n .Your task is to print number of numbers between a and b including them also which have n-divisors. A number is called n-divisor if it has total n divisors including 1 and itself. Examples: Input : a = 1, b = 7, n = 2 Output : 4 There are four numbers with 2 divisors in
14 min read
Count elements which divide all numbers in range L-R
The problem statement describes a scenario where we are given an array of N numbers and Q queries. Each query consists of two integers L and R, representing a range of indices in the array. The task is to find the count of numbers in the array that divide all the numbers in the range L-R. Examples :
15+ min read
Count the numbers divisible by 'M' in a given range
A and B are two numbers which define a range, where A <= B. Find the total numbers in the given range [A ... B] divisible by 'M'Examples: Input : A = 25, B = 100, M = 30 Output : 3 Explanation : In the given range [25 - 100], 30, 60 and 90 are divisible by 30 Input : A = 6, B = 15, M = 3 Output :
9 min read