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.
Example
Input: 55 Output: No Explanation: 5+5 = 10; 55 not divisible by 10 Input: 12 Output: Yes Explanation: 1+2 = 3; 12 is divisible by 3
The approach used below is as follows −
To solve this problem we have to fetch each digit from the input and find the sum of each digit of a number, then check whether it is dividing the number or not.
- Take input
- Take each number from the unit place using and add it to a sum variable which should be initially zero
- Divide the input with the sum of the number.
- Return the result.
Algorithm
In function int isDivisible(long int num) Step 1-> Declare and initialize temp = num, sum = 0 Step 2-> Loop While num Declare and initialize k as num % 10 Set sum as sum + k Set num as num / 10 End Loop Step 3-> If temp % sum == 0 then, Return 1 Step 4-> Return 0 End function In main() Step 1-> Declare and initialize num as 55 Step 2-> If isDivisible(num) then, Print "yes " Step 3-> Else Print "no "
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 num = 55; if(isDivisible(num)) printf("yes\n"); else printf("no\n"); return 0; }
Output
If run the above code it will generate the following output −
No