Count the Number of Divisors of n occurring within n in C++

In this tutorial, we will learn how to count the number of divisors of a number where that divisor is a digit of the number. Also, we will see its implementation in C++.

Divisor

An integer d is a divisor of an integer n if the remainder of n/d is zero i.e., n%d must be equal to zero.

Count Divisors occurring within n

Given an integer n as input, we need to count the number of divisors of n occurring within n.

Note: Each digit of the number n is considered to be unique. So, we should count all the occurrences of the same digit.

Example: if n=242, 2 is a divisor of 242. Every time 2 occurs in n we need to count it. It occurs twice, so the output is 2.

Implementation in C++

#include <iostream>
using namespace std;
int main ()
{
  int number, count, remainder, numberCopy;
  cout << "Enter a number" << endl;
    cin >> number;
    count = 0;
    numberCopy = number;
     
    while (numberCopy != 0)
    {
        remainder = numberCopy%10;
        numberCopy = numberCopy/10;
        if (remainder != 0)
        {
            if ((number%remainder) == 0)
            {
                count++;
            }
    }        
    }
    cout << "Number of divisors of the given number occurring within the given number are: " << count << endl;
    return 0;
}

Here, we are using the if condition ‘remainder != 0’ and checking that the ‘remainder’ is not equal to zero. This is because we don’t want to get into runtime errors when we are dividing ‘number’ by the ‘remainder’.

If the number is 233145, then 1,3,5 are the divisors that are present in the given number. Here, 3 is occurring twice. So, the total count becomes 4.

Output:

Enter a number
233145
Number of divisors of the given number occurring within the given number are: 4

 

Also read, Print prime numbers in C++

Leave a Reply

Your email address will not be published. Required fields are marked *