Search code examples
c++intmodulusdigits

Finding digits (in a number) that exactly divide the number


I am writing a program to find the number of digits in a number that exactly divide that number (remainder=0).

For example, for 145. There are 2 digits that divide 145, 1 and 5(145%2=0,145%1=0).

When a number contains a 0 as a digit, like 102, the program fails. I understand that I can't divide by zero, i tried to solve this, but the program is still not working. Any suggestions on how to avoid division by zero?

#include <iostream>

int main(){
std::cout<<"Enter a number: ";
int n,digit,count=0;
std::cin>>n;

    while(n){
        digit = n%10;
        if(digit==0) continue;
        else{
            if(n%(digit)==0) count++; n /= 10;}
    }

std::cout<<"Number of digits that divide the number: "<<count<<"\n"; count=0;
}

Solution

  •     int n , digit, count = 0;
        std::cin >> n;
        int cn = n;
    
        while (n){
    
            digit = n % 10;
            n /= 10;
    
            if (digit == 0) continue;
            else{
                if (cn % (digit) == 0) count++;             
            }
    
        }