Check if the sum of digits of number is divisible by all of its digits
Last Updated :
11 Jul, 2023
Given an integer N, the task is to check whether the sum of digits of the given number is divisible by all of its digits or not. If divisible then print Yes else print No.
Examples:
Input: N = 12
Output: No
Sum of digits = 1 + 2 = 3
3 is divisible by 1 but not 2.
Input: N = 123
Output: Yes
Approach: First find the sum of the digits of the number then one by one check, whether the calculated sum is divisible by all the digits of the number. If for some digit it is not divisible then print No else print Yes.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function that returns true if all the digits
// of n divide the sum of the digits of n
bool isDivisible(long long int n)
{
// Store a copy of the original number
long long int temp = n;
// Find the sum of the digits of n
int sum = 0;
while (n) {
int digit = n % 10;
sum += digit;
n /= 10;
}
// Restore the original value
n = temp;
// Check if all the digits divide
// the calculated sum
while (n) {
int digit = n % 10;
// If current digit doesn't
// divide the sum
if (sum % digit != 0)
return false;
n /= 10;
}
return true;
}
// Driver code
int main()
{
long long int n = 123;
if (isDivisible(n))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
// Java implementation of the approach
public class GFG
{
// Function that returns true if all the digits
// of n divide the sum of the digits of n
static boolean isDivisible(long n)
{
// Store a copy of the original number
long temp = n;
// Find the sum of the digits of n
int sum = 0;
while (n != 0)
{
int digit = (int) n % 10;
sum += digit;
n /= 10;
}
// Restore the original value
n = temp;
// Check if all the digits divide
// the calculated sum
while (n != 0)
{
int digit = (int)n % 10;
// If current digit doesn't
// divide the sum
if (sum % digit != 0)
return false;
n /= 10;
}
return true;
}
// Driver code
public static void main (String[] args)
{
long n = 123;
if (isDivisible(n))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by AnkitRai01
Python
# Python implementation of the approach
# Function that returns true if all the digits
# of n divide the sum of the digits of n
def isDivisible(n):
# Store a copy of the original number
temp = n
# Find the sum of the digits of n
sum = 0
while (n):
digit = n % 10
sum += digit
n //= 10
# Restore the original value
n = temp
# Check if all the digits divide
# the calculated sum
while(n):
digit = n % 10
# If current digit doesn't
# divide the sum
if(sum % digit != 0):
return False
n //= 10;
return True
# Driver code
n = 123
if(isDivisible(n)):
print("Yes")
else:
print("No")
C#
// C# implementation of the approach
using System;
class GFG
{
// Function that returns true if all the digits
// of n divide the sum of the digits of n
static bool isDivisible(long n)
{
// Store a copy of the original number
long temp = n;
// Find the sum of the digits of n
int sum = 0;
while (n != 0)
{
int digit = (int) n % 10;
sum += digit;
n /= 10;
}
// Restore the original value
n = temp;
// Check if all the digits divide
// the calculated sum
while (n != 0)
{
int digit = (int)n % 10;
// If current digit doesn't
// divide the sum
if (sum % digit != 0)
return false;
n /= 10;
}
return true;
}
// Driver code
static public void Main ()
{
long n = 123;
if (isDivisible(n))
Console.Write("Yes");
else
Console.Write("No");
}
}
// This code is contributed by @tushil.
JavaScript
<script>
// Javascript implementation of the approach
// Function that returns true if all the
// digits of n divide the sum of the digits
// of n
function isDivisible(n)
{
// Store a copy of the original number
var temp = n;
// Find the sum of the digits of n
var sum = 0;
while (n != 0)
{
var digit = parseInt(n % 10);
sum += digit;
n = parseInt(n / 10);
}
// Restore the original value
n = temp;
// Check if all the digits divide
// the calculated sum
while (n != 0)
{
var digit = parseInt(n % 10);
// If current digit doesn't
// divide the sum
if (sum % digit != 0)
return false;
n = parseInt(n/10);
}
return true;
}
// Driver code
var n = 123;
if (isDivisible(n))
document.write("Yes");
else
document.write("No");
// This code is contributed by todaysgaurav
</script>
Time Complexity: O(log(N))
Auxiliary Space: O(1)
Method #2: Using string:
- We have to convert the given number to a string by taking a new variable.
- Traverse the string ,Convert each element to integer and add this to sum.
- Traverse the string again
- Check if the sum is not divisible by any one of the digits
- If it is true then return False
- Else return True
Below is the implementation of above approach:
C++
// C++ implementation of above approach
#include <bits/stdc++.h>
using namespace std;
string getResult(int n)
{
// Converting integer to string
string st = to_string(n);
// Initialising sum to 0
int sum = 0;
int length = st.size();
// Traversing through the string
for (int i = 0; i < st.size(); i++) {
// Converting character to int
sum = sum + (int(st[i]) - 48);
}
// Comparing number and sum
// Traversing again
for (int i = 0; i < st.size(); i++) {
// Check if any digit is
// not dividing the sum
if (sum % (int(st[i]) - 48) != 0) {
// Return false
return "No";
}
// If any value is not returned
// then all the digits are dividing the sum
// SO return true
else {
return "Yes";
}
}
}
// Driver Code
int main()
{
int n = 123;
// passing this number to get result function
cout << getResult(n);
return 0;
}
// This code is contributed by subhamkumarm348.
Java
// Java implementation of the approach
import java.io.*;
import java.util.*;
class GFG
{
// Function that returns true if all the digits
// of n divide the sum of the digits of n
public static String getResult(int n)
{
// Converting integer to string
String st = String.valueOf(n);
// Initialising sum to 0
int sum = 0;
int length = st.length();
// Traversing through the string
for (int i = 0; i < length; i++)
{
// Converting character to int
int c = st.charAt(i)-48;
sum += c;
}
// Comparing number and sum
// Traversing again
for (int i = 0; i < length; i++)
{
// Check if any digit is
// not dividing the sum
int c = st.charAt(i)-48;
if (sum % c != 0)
{
// Return false
return "No";
}
// If any value is not returned
// then all the digits are dividing the sum
// SO return true
else
{
return "Yes";
}
}
return "No";
}
// Driver code
public static void main (String[] args)
{
int n = 123;
// passing this number to get result function
System.out.println(getResult(n));
}
}
// This code is contributed by aditya942003patil
Python3
# Python implementation of above approach
def getResult(n):
# Converting integer to string
st = str(n)
# Initialising sum to 0
sum = 0
length = len(st)
# Traversing through the string
for i in st:
# Converting character to int
sum = sum + int(i)
# Comparing number and sum
# Traversing again
for i in st:
# Check if any digit is
# not dividing the sum
if(sum % int(i) != 0):
# Return false
return 'No'
# If any value is not returned
# then all the digits are dividing the sum
# SO return true
return 'Yes'
# Driver Code
n = 123
# passing this number to get result function
print(getResult(n))
# this code is contributed by vikkycirus
C#
// C# program to implement above approach
using System;
using System.Collections.Generic;
class GFG
{
static string getResult(int n)
{
// Converting integer to string
string st = n.ToString();
// Initialising sum to 0
int sum = 0;
int length = st.Length;
// Traversing through the string
for (int i = 0; i < length; i++) {
// Converting character to int
sum = sum + ((int)st[i] - 48);
}
// Comparing number and sum
// Traversing again
for (int i = 0; i < length; i++) {
// Check if any digit is
// not dividing the sum
if (sum % ((int)st[i] - 48) != 0) {
return "No";
}
// If any value is not returned
// then all the digits are dividing the sum
// SO return true
else {
return "Yes";
}
}
return "No";
}
// Driver Code
public static void Main(string[] args){
int n = 123;
// Function call
Console.Write(getResult(n));
}
}
// This code is contributed by adityapatil12.
JavaScript
<script>
// JavaScript implementation of above approach
function getResult(n){
// Converting integer to string
var st = n.toString();
// Initialising sum to 0
var sum = 0
var length = st.length;
// Traversing through the string
for (var i= 0 ;i<st.length ; i++){
// Converting character to int
sum = sum + Number(st[i])
}
// Comparing number and sum
// Traversing again
for( var i = 0 ; i < st.length ; i++){
// Check if any digit is
// not dividing the sum
if(sum % Number(st[i]) != 0){
// Return false
return 'No'
}
// If any value is not returned
// then all the digits are dividing the sum
// SO return true
else{
return 'Yes';
}
}
}
// Driver Code
var n = 123;
// passing this number to get result function
document.write(getResult(n));
</script>
Time Complexity: O(n), where n represents the length of the given string.
Auxiliary Space: O(d), where d represents the number of digits in the string.
Approach 3: Dynamic Programming:
The dynamic programming approach to check if a number is divisible by the sum of its digits works as follows:
- Convert the given number to a string.
- Calculate the sum of the digits of the number.
- Initialize a boolean array dp of size sum+1, where dp[i] indicates whether it is possible to obtain a sum of i using some of the digits of the number.
- Initialize dp[0] to true, since it is always possible to obtain a sum of 0 using no digits.
- Traverse the digits of the number one by one. For each digit, traverse the dp array from right to left and update the values of dp[i] as follows:
a. If i is less than the current digit, then dp[i] remains unchanged.
b. If i is greater than or equal to the current digit, then dp[i] is updated as dp[i] || dp[i - digit], where digit is the current digit. - Return dp[sum], which indicates whether it is possible to obtain a sum of sum using some of the digits of the number.
- If dp[sum] is true, then the sum of the digits of the number is divisible by the number itself, otherwise it is not divisible.
Here is the code for above approach:
C++
// C++ implementation of above approach
#include <bits/stdc++.h>
using namespace std;
// Dynamic programming approach to check if a number is divisible
// by the sum of its digits
bool isDivisible(int n)
{
// Convert the number to string
string str = to_string(n);
// Calculate the sum of digits
int sum = 0;
for (char c : str) {
sum += (c - '0');
}
// If the sum is 0, return false
if (sum == 0) {
return false;
}
// Initialize the dp array
bool dp[sum + 1];
memset(dp, false, sizeof(dp));
dp[0] = true;
// Traverse the digits of the number
for (char c : str) {
int digit = c - '0';
for (int i = sum; i >= digit; i--) {
dp[i] = dp[i] || dp[i - digit];
}
}
// Return true if the sum is divisible by the number
return dp[sum];
}
int main()
{
long long int n = 123;
if (isDivisible(n))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
import java.util.Arrays;
public class Main {
// Dynamic programming approach to check if a number is divisible
// by the sum of its digits
static boolean isDivisible(int n) {
// Convert the number to string
String str = Integer.toString(n);
// Calculate the sum of digits
int sum = 0;
for (char c : str.toCharArray()) {
sum += (c - '0');
}
// If the sum is 0, return false
if (sum == 0) {
return false;
}
// Initialize the dp array
boolean[] dp = new boolean[sum + 1];
Arrays.fill(dp, false);
dp[0] = true;
// Traverse the digits of the number
for (char c : str.toCharArray()) {
int digit = c - '0';
for (int i = sum; i >= digit; i--) {
dp[i] = dp[i] || dp[i - digit];
}
}
// Return true if the sum is divisible by the number
return dp[sum];
}
public static void main(String[] args) {
int n = 123;
if (isDivisible(n)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
}
Python3
class Program:
@staticmethod
def IsDivisible(n):
# Convert the number to string
str_n = str(n)
# Calculate the sum of digits
digit_sum = sum(int(digit) for digit in str_n)
# If the sum is 0, return False
if digit_sum == 0:
return False
# Initialize the dp array
dp = [False] * (digit_sum + 1)
dp[0] = True
# Traverse the digits of the number
for digit_char in str_n:
digit = int(digit_char)
for i in range(digit_sum, digit - 1, -1):
dp[i] = dp[i] or dp[i - digit]
# Return True if the sum is divisible by the number
return dp[digit_sum]
@staticmethod
def Main():
n = 123
if Program.IsDivisible(n):
print("Yes")
else:
print("No")
# This code is contributed by Shivam Tiwari
# Run the program
Program.Main()
C#
using System;
public class Program
{
// Dynamic programming approach to check if a number is divisible
// by the sum of its digits
public static bool IsDivisible(long n)
{
// Convert the number to string
string str = n.ToString();
// Calculate the sum of digits
int sum = 0;
foreach (char c in str)
{
sum += (c - '0');
}
// If the sum is 0, return false
if (sum == 0)
{
return false;
}
// Initialize the dp array
bool[] dp = new bool[sum + 1];
dp[0] = true;
// Traverse the digits of the number
foreach (char c in str)
{
int digit = c - '0';
for (int i = sum; i >= digit; i--)
{
dp[i] = dp[i] || dp[i - digit];
}
}
// Return true if the sum is divisible by the number
return dp[sum];
}
public static void Main()
{
long n = 123;
if (IsDivisible(n))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
// This code is contributed by Shivam Tiwari
}
}
JavaScript
// Dynamic programming approach to check if a number is divisible
// by the sum of its digits
function isDivisible(n) {
// Convert the number to string
let str = n.toString();
// Calculate the sum of digits
let sum = 0;
for (let i = 0; i < str.length; i++) {
sum += parseInt(str[i]);
}
// If the sum is 0, return false
if (sum === 0) {
return false;
}
// Initialize the dp array
let dp = new Array(sum + 1).fill(false);
dp[0] = true;
// Traverse the digits of the number
for (let i = 0; i < str.length; i++) {
let digit = parseInt(str[i]);
for (let j = sum; j >= digit; j--) {
dp[j] = dp[j] || dp[j - digit];
}
}
// Return true if the sum is divisible by the number
return dp[sum];
}
let n = 123;
if (isDivisible(n)) {
console.log("Yes");
} else {
console.log("No");
}
Output
Yes
Time Complexity: O(SN), where S is the sum of the digits of the number and N is the number of digits in the number.
Auxiliary Space: O(S), as we are using a boolean array of size S+1 to store the intermediate results of the subproblems.
Similar Reads
Program to check if a number is divisible by sum of its digits
Given an integer N, the task is to check whether the number is divisible by the sum of its digits or not. If divisible, then print âYESâ else print âNOâ. Examples: Input: N = 12 Output: YES Explanation: As sum of digits of 12 = 1 + 2 = 3 and 12 is divisible by 3 So the output is YES Input: N = 123 O
7 min read
Program to check if a number is divisible by any of its digits
Given an integer N where 1 \leq n \leq 10^{18} . The task is to check whether the number is not divisible by any of its digit. If the given number N is divisible by any of its digits then print "YES" else print "NO". Examples: Input : N = 5115Output : YESExplanation: 5115 is divisible by both 1 and
10 min read
Check if the sum of digits of a number N divides it
Given a number n, the task is to check if the sum of digits of the given number divides the number or not. Examples: Input : n = 12Output : YesExplanation: Sum of digits = 1+2 =3 and 3 divides 12.Input : n = 15Output : NoExplanation: Sum of digits = 1+5 =6 and 15 % 6 != 0.Using Iterative Method - O(
6 min read
Check whether sum of digits at odd places of a number is divisible by K
Given two integers 'N' and 'K', the task is to find the sum of digits of 'N' at its odd places (right to left) and check whether the sum is divisible by 'K'. If it is divisible, output YES, otherwise output NO. Examples: Input: N = 4325, K = 4 Output: YES Since, 3 + 5 = 8, which is divisible by 4. I
7 min read
Count numbers in range whose sum of digits is divisible by XOR of digits
Given integers L and R, the task for this problem is to find a number of integers in the range L to R whose sum of digits is divisible by bitwise XOR of digits. print the answer. ( L <= R <= 1018) Note: Bitwise XOR sum zero never divides any other number. Examples: Input: L = 10, R = 15Output:
15+ min read
Check if all prefixes of a number is divisible by remaining count of digits
Given a number N, the task is to check if for every value of i (0 <= i <= len), the first i digits of a number is divisible by (len - i + 1) or not, where len is the number of digits in N. If found to be true, then print "Yes". Otherwise, print "No". Examples: Input: N = 52248.Output: YesExpla
4 min read
Check if a given number divides the sum of the factorials of its digits
Given an integer N, the task is to check whether N divides the sum of the factorials of its digits.Examples: Input: N = 19 Output: Yes 1! + 9! = 1 + 362880 = 362881, which is divisible by 19.Input: N = 20 Output: No 0! + 2! = 1 + 4 = 5, which is not divisible by 20. Approach: First, store the factor
9 min read
Find a N-digit number such that it is not divisible by any of its digits
Given an integer N, the task is to find an N-digit number such that it is not divisible by any of its digits.Note: There can be multiple answers for each value of N. Examples: Input: N = 4 Output: 6789 Explanation: As the number 6789 is not divisible by any of its digits, it is 6, 7, 8 and 9 and it
5 min read
Find a N-digit number such that it is not divisible by any of its digits
Given an integer N, the task is to find any N-digit positive number (except for zeros) such that it is not divisible by any of its digits. If it is not possible to find any such number then print -1.Note: There can be more than one such number for the same N-digit. Examples: Input: N = 2 Output: 232
7 min read
Check whether product of digits at even places is divisible by sum of digits at odd place of a number
Given a number N and numbers of digits in N, the task is to check whether the product of digits at even places of a number is divisible by sum of digits at odd place. If it is divisible, output "TRUE" otherwise output "FALSE". Examples: Input: N = 2157 Output: TRUESince, 1 * 7 = 7, which is divisibl
13 min read