
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count Digits in Given Number N Which Divide N in C++
We are given a number let’s say, N and the task is to find the count of those digits in a number that divides the number N.
Points to be remember
If the digit is 0 then it should be ignored which means count will not be increased for 0.
If a digit is appearing twice and it divides the number, then the count will depend upon the digit occurrence. For example, we are given a number 2240 and in this number every digit except the 0 will divide the number and 2 is occurring twice then the count will be 2 for digit 2.
Input − number = 2240
Output − count is 3
Explanation − Break the number into digits and it will be 2, 2, 4, 0. Now check whether 2 divides 2240 if yes then increase the count else move to next digit, in this number 2, 2, 4 divides the digit 2240 so count will be 3 and ignore the digit 0 in every case.
Input − number = 755
Output − count is 2
Explanation − Break the number into digits and it will be 7, 5, 5. Now check whether 7 divides 755 if yes then increase the count else move to next digit, in this number 5, 5 divides the digit 755 so count will be 2 and ignore the digit 0 in every case
Approach used in the below program is as follows
Input the number in a integer variable let’s say num
Start the loop till num is greater than 0
Inside the loop, break the number into digits and keep storing the results in a variable let’s say rem
Check if rem divides the number if yes then increase the value of a count variable by 1 and if not then don’t increase the value of a count variable.
And this check statement is applied when the rem is greater than 0 as we have to ignore the 0.
Example
#include <bits/stdc++.h> using namespace std; int count(int num){ int a=num; int count=0,rem; while(a>0){ rem=a%10; if(rem > 0){ if(num%rem==0){ count++; } } a=a/10; } return count; } int main(){ int num = 2240; cout<<"Count of digits in given number "<<num<<" which divide N are: "<<count(num); return 0; }
Output
If we run the above code, we will get the following output −
Count of digits in given number 2240 which divide N are: 3