Given a number n, we need to check whether the sum of its digits is divisible by n. To find out, we need to add all the numbers starting from the ones digit and then divide the final sum by that number.
For example, we have a number "521", and we need to find the sum of its digits, that is, "5 2 1 = 8", but 521 cannot be divided by 8, and the remainder is not 0.
Another example, "60", the sum of its digits is "6 0 = 6", 6 can be divided into 60, and the remainder is 0.
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 method used below is as follows: −
To solve this problem, we need to get each number from the input and calculate Sum each number and then check if it divides the number.
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 "
Demonstration
#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</p><p>"); else printf("no</p><p>"); return 0; }
If you run the above code, the following output will be generated −
No
The above is the detailed content of C program to check if a number is divisible by the sum of its digits. For more information, please follow other related articles on the PHP Chinese website!