how to divide sum of number by digit on number?

Question:

how to divide num of digit by digit number?

e.g : 4228 is true because 4+2+2+8=16 can divide by 4, 2, 8

3425 false because 3+4+2+5=14 can’t divide by 3, 4, 2, 5

numbers = int(input('input number : '))
result = 0

# NUM of digit
while numbers > 0 :
    digit = numbers % 10
    result = result + digit
    numbers = numbers // 10

factors = result

#factors of "NUM of digit"
for factor_result in range(1,factors + 1) :
    if factors % factor_result == 0 :
        print(factor_result)

please help me;(

thank you a lot:))

Asked By: daylooo

||

Answers:

num = 4220
res = [int(x) for x in str(num)]

can_devided = True
for r in res:
    if r == 0:
        continue
    if sum(res) % r != 0:
        can_devided = False
        

print (can_devided)

From your description it sounds like you want a function like this

# determine if sum of integers comprising an integer is divisible by its part
def divisor_check(num):
    # check that input num is integer 
    if not isinstance(num,int):
       print('warning: input is not an integer')
       return False

    # break num into component integers by convert to string first
    stringafied_num = str(num)
    
    # split the string-afied num to get component integers
    components = [*stringafied_num]
    
    # evaluate the components to get integers back
    components = [eval(v) for v in components]
    
    # sum components
    total=sum(components)
    
    # try dividing total by each component 
    for c in components:
        if total%c != 0:
            return False
    return True

This function breaks up the input into its component integers, sums them, and computes the desired divisor check.

If you evaluate this function for your examples you get the desired results

divisor_check(4228) --> True

divisor_check(3425) --> False

Answered By: neonwatty

A simple way to do it is to calculate the sum of the digits then check if the modulo is 0.

In python, we could parse the number to a str, then convert every digit (which is a single char) back to an int and create a list of these digits

input_numbers = int(input('input number : '))

# parse the number to a str, then map each char back to an integer
# and create a list of int for each digit
numbers = list(map(int, str(input_numbers )))    

Now, just use the built-in sum() method to get the result you wish. The next part is just a loop over every digit on the numbers list and check the module.

result = sum(numbers)

is_divisible = True
for number in numbers:
  if number == 0 or result % int(number) != 0:
    is_divisible = False
print(is_divisible)
Answered By: Gabriel Caldas
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.