# Am I divisible by double the sum of my digits?

Given a positive integer as input, your task is to output a truthy value if the number is divisible by the double of the sum of its digits, and a falsy value otherwise (OEIS A134516). In other words:

(sum_of_digits)*2 | number

• Instead of truthy / falsy values for the true and false cases, you may instead specify any finite set of values for the true/false case, and their complement the other values. For a simple example, you may use 0 for the true case and all other numbers for the false case (or vice versa, if you like).

• Standard input and output rules apply. Default Loopholes also apply.

• You can take input as an integer or as the string representation of that integer.

• This is , hence the shortest code in bytes wins!

• I am new to PPCG, so I would like you to post an explanation if it's possible.

# Test Cases

Input - Output - (Reason)

80  - Truthy - (16 divides 80)
100 - Truthy - (2 divides 100)
60  - Truthy - (12 divides 60)
18 - Truthy - (18 divides 18)
12 - Truthy - (6 divides 12)

4 - Falsy - (8 does not divide 4)
8 - Falsy - (16 does not divide 8)
16  - Falsy  - (14 does not divide 16)
21 - Falsy - (6 does not divide 21)
78  - Falsy  - (30 does not divide 78)
110 - Falsy - (4 does not dide 110)
111 - Falsy - (6 does not divide 111)
390 - Falsy  - (24 does not divide 390)

• Good challenge, welcome to PPCG! Jul 3, 2017 at 13:59
• @Mayube Thanks, it is my second challenge, but the first one got closed :P
– user70974
Jul 3, 2017 at 14:00
• Are we allowed to take digits as a list of Integers? Jul 3, 2017 at 14:32
• @Henry No, that would be way too trivial
– user70974
Jul 3, 2017 at 14:34
• Indeed, the two sentences of "Instead of truthy / falsy values for the true and false cases, you may instead specify any finite set of values for the true case, and their complement for the falsy ones. For a simple example, you may use 0 for the true case and all other numbers for the false case (or vice versa, if you like)" seem to contradict each other (in particular, the "finite" and the "or vice versa"). Jul 4, 2017 at 2:52

# jq, 37 characters

.%(tostring/""|map(tonumber)|add*2)<1


Sample run:

bash-4.4$jq '.%(tostring/""|map(tonumber)|add*2)<1' <<< '60' true bash-4.4$ jq '.%(tostring/""|map(tonumber)|add*2)<1' <<< '390'
false


Try on jp‣play

yes $1%$$0echo 1|sed 's/\(.$$/+\1*2/g'\)|bc  Input via command line. 0 is truthy. First I tried to loop through the characters of the input string, but bash loops are to big. I ended up using sed to replace each character with an addition and multiplication, which then goes to bc. I saved a byte using yes instead of echo. # Perl 5, 27 bytes $_%(2*eval join'+',split//)


Returns 0 for Truthy and non-zero for Falsy

• Welcome on the site. Answers need to be either full programs or functions, while your answer is only a snippet. To make it a full program, you could add -p flag (cost 1 byte), and start with $_%=(2*...). Also, join'+',split// can be simplified to join'+',@F is you use -F  flag, or even better, s/./+$&/gr :)
Jul 4, 2017 at 9:21

# CJam, 11 10 bytes

1 byte saved thanks to @Challenger5

{_Ab:+2*%}


Anonymous block that takes the input from the stack and replaces it by the output, which is 0 if divisible or a positive integer otherwise.

### Explanation

{        }   e# Block
_           e# Duplicate
Ab         e# Convert to base 10. Gives an array of digits
:+       e# Fold addition over array
2*     e# Multiply by 2
%    e# Modulus

• You can replace s:~ with Ab (convert to base 10) Jul 4, 2017 at 6:36
• @Challenger5 Thanks! Edited Jul 4, 2017 at 8:26

## LOGO, 24 bytes

[modulo ? 2*reduce "+ ?]


Try it online!
Only FMSLogo and its older version (MSWLogo) support ? in template-list; and only FMSLogo supports apply for infix operator +.

That is a template-list (equivalent of lambda function in other languages). Return 0 for truthy and other values for falsy.

Usage:

pr invoke [modulo ? 2*reduce "+ ?] 100


(invoke calls the function, pr prints the result)

Explanation:

There is only one points need explaining: reduce. That is similar to fold in some other languages: reduce "f [1 2 3 4] calculate (f (f (f 1 2) 3) 4). In this case, reduce "+ ? calculate total of elements of digits in ?.

Numbers in LOGO is represented by word, so reduce, a library function can receive a word as its second parameter (while apply can't)

## Alice, 16 bytes

/o. &
\i@h /+.+F


Try it online!

Prints twice the digit sum as the truthy result and 0 otherwise.

The code looks so painfully suboptimal with the two spaces and the repeated . and +, but I just can't figure out a more compact layout.

### Explanation

/    Switch to Ordinal mode.
i    Read all input as a string.
.    Duplicate.
h    Split off the first character.
&    Fold the next command over the remaining characters (i.e. push each character
in turn and then execute the command).
/    Switch back to Cardinal mode (not a command).
+    Add. This is folded over the characters, which implicitly converts them
to the integer value they represent and adds them to the leading digit.
.+   Duplicate and add, to double the digit sum.
F    Test for divisibility. Gives 0 if the input is not divisible by twice its
digit sum and the (positive/truthy) divisor otherwise.
\    Switch to Ordinal mode.
o    Implicitly convert the result to a string and print it.
@    Terminate the program.


# Pyth, 7 bytes

%QyssM


Test it online! It returns 0 for truthy, a non null positive integer for falsy.

Explanations

       Q    # Implicit input Q
# Convert the input to a string
sM      # For each character in Q, convert to integer
s        # Sum the resulting list
y         # Multiply by two
%Q          # Perform the modulo with the input


# Java, 53 bytes

a->{int i=0,c=a;for(;c>0;c/=10)i+=c%10*2;return a%i;}


0 true

>0 false

• Welcome to PPCG! Jul 5, 2017 at 8:10

# R, 71 bytes

f=function(x)if(x%%(sum(floor(x/10^(0:(nchar(x)-1)))%%10)*2)==0,T,F)


Using floor(x/10^(0:(nchar(x)-1)))%%10 saves the usual hassle of converting to character and back.

> f(1)
[1] FALSE
> f(12)
[1] TRUE
> f(123456789)
[1] FALSE


# ><>, 26 bytes

000\~2*%n;
0(?\c%:{a*+}+i:


Try it online!

Output is 0 for truthy, non-0 for falsey.

## R, 58 bytes

(a<-scan())%%(2*sum(strtoi(el(strsplit(paste(a),"")))))<1


a <- scan() stores user's input in variable a.

This variable is of type numeric. The paste function converts it into character for the strsplit function to separate its digits. el permits to use only the first element of the list created by strsplit.

The strtoi function converts then the digits back into numeric, for the function sum to, well, sum, before doubling the result.

To finish, divisibility of a with the double sum of its digits is tested by the ... %% ... < 1 part, outputing TRUE or FALSE.

# Excel VBA, 72 Bytes

Anonymous VBE immediate window function that takes input from cell [A1] and outputs to the VBE immediate window

For i=1To[Len(A1)]:s=s+Int(Mid([A1],i,1)):Next:s=s*2:?Int([A1]/s)=[A1]/s


# Element, 29 bytes

Here goes my first "real" codegolf attempt...

_2:x;2:$'0 z;[(z~+z;]x~z~2*%  Outputs "0" if true, anything else if false. Try it online! Explanation: _ push input into main stack 2: pop number and push it twice x; store one of them as x 2: pop again and push twice$'            pop and get length, push it to control stack
0 z;          initiate accumulator "z" with value zero
[             for length of input number (loop start),
(             pop off first digit,
z~            retrieve "z",
+             add popped digit to it,
z;            store "z"  again
]             (end of looped statement)
x~            retrieve "x" (copy of original number)
z~            retrieve "z" (accumulated digit sum)
2*            double accumulated digit sum
%             modulus the digit sum and original number
pop result to output.


# K (oK), 14 bytes

Solution:

(2*+/48!$x)!x:  Try it online! Examples:  (2*+/48!$x)!x:18
0
(2*+/48!$x)!x:123 3 (2*+/48!$x)!x:390
6


Explanation:

Evaluation is performed right-to-left, unfortunately modulo is b!a rather than a!b hence the need for brackets. Returns 0 for truthy, positive integer for falsey per spec.

(2*+/48!$x)!x: / the solution x: / store input in variable x ! / modulo right by the left ( e.g. 3!10 => 1, aka 10 mod 3 ) ( ) / the left$x     / string ($) input, 123 => "123" 48! / modulo with 48, "123" => 1 2 3 +/ / sum over, +/1 2 3 => 6 2* / double, 6 => 12  Notes: • Prepend solution with ~ (not) to give a true/false result. # Ruby, 25 bytes ->x{x%(x.digits.sum*2)<1}  Try it online! # ><>, 36 Bytes Unlike the other ><> response, this takes the number itself as input as opposed to the digits. Of course, because of that it's a bit longer longer. :&>:a%:}-\1-?\2*&$%n;
\?)0:,a/l +<


### Explanation:

:&


Duplicates input, stores a copy in the register.

  >:a%:}-\
\?)0:,a/


Converts the number into its digits.

         \1-?\
/l +<


Sum the digits

              2*&\$%n;


Multiplies the digit sum by 2, and prints the original number modulo that sum. Output is, then, 0 for truthy and something else otherwise.

# Java 7, 197133 126 bytes

First try Second try, fixed it, -9 characters on variable name, and changing it into function for the other subtraction with help of Olivier Grégoire

Changed boolean to int, now return 0 for true values, other number for falsy

int b(String a){int t=0;for(int i=0;i<a.length();i++){t+=Integer.parseInt(""+a.charAt(i));}return(Integer.parseInt(a)%(t*2));}


boolean a(String a){int t=0;for(int i=0;i<a.length();i++){t+=Integer.parseInt(""+a.charAt(i));}return(Integer.parseInt(a)%(t*2)==0);}


Ungolfed

int b(String a){
int t=0;for(int i=0;i<a.length();i++){
t+=Integer.parseInt(""+a.charAt(i));
}
return(Integer.parseInt(a)%(t*2));}

• Hello and welcome to the golfing part of codegolf! First you can get a lot of tips from this thread to help you getting started. So let's golf, shall we? You're not forced to write full programs: you can write only a function, or if you use Java 8+, a lambda. Make sure to give short variable names and remove all your unneeded spaces (A { can be written as A{; String[] args as String[]a). You can return results instead of printing. The code doesn't pass the test cases of the challenge, fixing it would be 1st. Jul 4, 2017 at 18:02
• Hello, which test case didn't it pass? About only a function, I have read other post that says you have to create full executable program, this includes imports if you use them, correct me if I'm wrong, thank you :) Jul 5, 2017 at 7:01
• Ah, I forgot to multiply it *2 sorry Jul 5, 2017 at 7:04
• Fixed and changed to a function, thank you Jul 5, 2017 at 7:16

# Deorst, 16 bytes

iE"E|miEH:+zE|%N


Try it online!

## How it works

Implicitly inputs and outputs, example: 172

iE"              - To string;  STACK = ['172']
E|            - Splat;      STACK = ['1' '7' '2']
mi          - To integer; STACK = [1 7 2]
EH        - Sum;        STACK = [10]
:+      - Double;     STACK = [20]
zE|   - Push input; STACK = [20 172]
%N - Divides?    STACK = [0]


# ARBLE, 33 bytes

nt(a%(sum(explode(""..a,"."))*2))


Try it online!

# Julia, 30 29 bytes

f(x)=x/2sum(digits(x)) in 0:x


saved a byte thanks to caird-coinheringaahing

• This seems to fail for 60: Try it online! Nov 23, 2017 at 14:01
• you're right, the problem was order of operations. fixed it by saving a byte, thanks! Nov 23, 2017 at 18:47

# Clojure, 59 bytes

(fn[n](= 0(rem n(* 2(apply +(map #(-(int %)48)(str n)))))))


(defn sum-of-digits? [n]
(let [ds (map #(- (int %) 48) (str n)) ; Stringify n, and parse each digit char of the string
d-sum (* 2 (apply + ds))] ; Get the doubled sum
(= 0 (rem n d-sum)))) ; Check if the remainder of (/ n sum) is 0


# Scala, 54 32 bytes

Saved 22 bytes thanks to the comment of @user

Try it online!

n=>n.toInt%(n+n:\0)(_.asDigit+_)

• You should be able to use a lambda here. Also, n.concat(n) can be replaced with (n+n). Lastly, folding is shorter than map+sum. 32 bytes: n=>n.toInt%(n+n:\0)(_.asDigit+_)
– user
May 11, 2023 at 3:21