C Program to check if a number is divisible by any of its digits

Given a number n, the task is to find if any digit in the number divides the number completely. For example, the number 128625 is divisible by 5, which is also present in the number.

Syntax

int isDivisibleByDigit(long long int n);

Algorithm

The approach used is as follows −

  • Extract each digit from the number using modulo operation
  • Check if the original number is divisible by that digit
  • If divisible, return true; otherwise continue with the next digit
  • Remove the last digit by dividing the number by 10
  • Repeat until all digits are processed

Example

#include <stdio.h>

int divisible(long long int n) {
    long long int temp = n;
    
    while (n) {
        int k = n % 10;
        
        // Skip zero digits to avoid division by zero
        if (k != 0 && temp % k == 0)
            return 1;
        
        n /= 10;
    }
    return 0;
}

int main() {
    long long int n = 654123;
    
    printf("Number: %lld<br>", n);
    
    if (divisible(n)) {
        printf("Yes, the number is divisible by at least one of its digits<br>");
    } else {
        printf("No, the number is not divisible by any of its digits<br>");
    }
    
    return 0;
}
Number: 654123
Yes, the number is divisible by at least one of its digits

Example with Different Test Cases

Let's test the function with multiple numbers to see different scenarios −

#include <stdio.h>

int divisible(long long int n) {
    long long int temp = n;
    
    while (n) {
        int k = n % 10;
        
        if (k != 0 && temp % k == 0)
            return 1;
        
        n /= 10;
    }
    return 0;
}

int main() {
    long long int numbers[] = {53142, 223, 128625, 456};
    int size = 4;
    
    for (int i = 0; i < size; i++) {
        printf("Number: %lld - ", numbers[i]);
        
        if (divisible(numbers[i])) {
            printf("Yes<br>");
        } else {
            printf("No<br>");
        }
    }
    
    return 0;
}
Number: 53142 - Yes
Number: 223 - No
Number: 128625 - Yes
Number: 456 - Yes

Key Points

  • Always check for zero digits to avoid division by zero error
  • The function returns 1 (true) as soon as it finds a divisible digit
  • Time complexity is O(d) where d is the number of digits
  • Space complexity is O(1) as only constant extra space is used

Conclusion

This program efficiently checks if a number is divisible by any of its non-zero digits. The algorithm extracts each digit and performs modulo operation to determine divisibility, making it a simple yet effective solution.

Updated on: 2026-03-15T12:20:24+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements