Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
C Program to check if a number is divisible by sum of its digits
Given a number n we have to check whether the sum of its digits divide the number n or not. To find out we have to sum all the numbers starting from the unit place and then divide the number with the final sum.
Like we have a number "521" so we have to find the sum of its digit that will be "5 + 2 + 1 = 8" but 521 is not divisible by 8 without leaving any remainder.
Let's take another example "60" where "6+0 = 6" which can divide 60 and will not leave any remainder.
Syntax
int isDivisible(long int num);
Algorithm
The approach used below is as follows −
- Take input number
- Extract each digit from the unit place and add it to a sum variable which should be initially zero
- Check if the original number is divisible by the sum of digits
- Return the result
Example
#include <stdio.h>
// This function will check
// whether the given number is divisible
// by sum of its digits
int isDivisible(long int num) {
long int temp = num;
// Find sum of digits
int sum = 0;
while (num) {
int k = num % 10;
sum = sum + k;
num = num / 10;
}
// check if sum of digits divides num
if (temp % sum == 0)
return 1;
return 0;
}
int main() {
long int num1 = 55;
long int num2 = 12;
printf("Testing %ld: ", num1);
if(isDivisible(num1))
printf("Yes<br>");
else
printf("No<br>");
printf("Testing %ld: ", num2);
if(isDivisible(num2))
printf("Yes<br>");
else
printf("No<br>");
return 0;
}
Testing 55: No Testing 12: Yes
How It Works
- For 55: Sum of digits = 5 + 5 = 10; 55 ÷ 10 = 5.5 (not divisible)
- For 12: Sum of digits = 1 + 2 = 3; 12 ÷ 3 = 4 (divisible)
Conclusion
This program efficiently checks divisibility by extracting each digit using modulo operation and building the sum. The time complexity is O(log n) where n is the input number.
Advertisements
