| Bytes | Lang | Time | Link |
|---|---|---|---|
| 045 | Tcl | 170703T180604Z | sergiol |
| 5432 | Scala | 230508T013938Z | 138 Aspe |
| 047 | Lua | 230507T023007Z | bluswimm |
| 003 | Thunno 2 | 230506T132528Z | The Thon |
| 021 | Arturo | 230506T020103Z | chunes |
| 039 | Knight | 220825T005253Z | Aiden Ch |
| 062 | Desmos | 220825T003317Z | Aiden Ch |
| 121 | C++ | 220304T040332Z | oeuf |
| 046 | Swift | 220303T015942Z | Bbrk24 |
| 003 | Vyxal | 220302T191629Z | Larry Ba |
| 037 | Factor + math.text.utils math.unicode | 211231T172211Z | chunes |
| 037 | Zsh | 210119T083916Z | pxeger |
| 103 | Whitespace | 210119T080724Z | Kevin Cr |
| 003 | MathGolf | 210119T074505Z | Kevin Cr |
| 003 | Vyxal | 201011T053306Z | lyxal |
| 005 | Husk | 201011T044227Z | Razetime |
| 014 | K ngn/k | 190822T195254Z | scrawl |
| 011 | Keg+Reg | 190824T084727Z | user8505 |
| 058 | Forth gforth | 190822T201721Z | reffu |
| 011 | Runic Enchantments | 190822T200144Z | Draco18s |
| 034 | Befunge93 | 171129T040820Z | Jo King |
| 007 | Brachylog | 190302T024357Z | Unrelate |
| 059 | Clojure | 171129T000355Z | Carcigen |
| 012 | Pyth 12 Bytes | 171127T163304Z | Tornado5 |
| 029 | Julia | 171121T142927Z | EricSher |
| 033 | ARBLE | 171123T230601Z | ATaco |
| 016 | Deorst | 171122T152528Z | caird co |
| 126 | Java 7 | 170704T133535Z | Java Gon |
| 010 | Ly | 171122T092854Z | LyricLy |
| 036 | ><> | 171122T080258Z | Bolce Bu |
| 025 | Ruby | 170704T061240Z | G B |
| 011 | Add++ | 171122T073833Z | caird co |
| 014 | K oK | 171121T153218Z | mkst |
| 003 | Neim | 170703T130213Z | Okx |
| nan | Perl 5 | 170816T154920Z | Xcali |
| 051 | C# .NET Core | 170816T141051Z | jkelm |
| 040 | Java OpenJDK 8 | 170716T104210Z | Nevay |
| 029 | Element | 170716T051703Z | aAaa aAa |
| 021 | TIBASIC | 170703T174605Z | Scott Mi |
| 072 | Excel VBA | 170715T164057Z | Taylor R |
| 013 | APL | 170710T203036Z | Uriel |
| 058 | R | 170708T155441Z | Rudier |
| 026 | ><> | 170710T125219Z | Sok |
| 071 | R | 170708T125922Z | Andrew H |
| 292 | MiniFlak | 170704T150004Z | user2027 |
| 024 | x8664 Machine Code | 170704T100540Z | Cody Gra |
| 053 | C89 | 170704T113054Z | Cody Gra |
| 035 | Python 3 | 170704T152533Z | wrymug |
| 053 | Java OpenJDK 8 | 170704T174303Z | Olivier |
| 044 | PHP | 170705T094239Z | aross |
| 053 | Java | 170705T074503Z | Krzyszto |
| 042 | Haskell | 170703T164717Z | Julian W |
| 007 | Pyth | 170704T165444Z | Jim |
| 034 | Haskell | 170704T063911Z | bartavel |
| 016 | Alice | 170704T113702Z | Martin E |
| 024 | LOGO | 170704T112140Z | user2027 |
| 004 | 05AB1E | 170703T132326Z | Datboi |
| 010 | CJam | 170703T214322Z | Luis Men |
| 027 | Perl 5 | 170703T225209Z | jmatix |
| 046 | Bash + coreutils + bc | 170703T215314Z | It Guy |
| 039 | PowerShell | 170703T202608Z | Tessella |
| 008 | Husk | 170703T163029Z | Martin E |
| 019 | Perl 6 | 170703T160856Z | Sean |
| 004 | Japt | 170703T132553Z | Shaggy |
| 005 | Ohm | 170703T153804Z | FrodCube |
| 015 | J | 170703T152142Z | Alex Shr |
| 037 | jq | 170703T152944Z | manatwor |
| 007 | MATL | 170703T132625Z | Luis Men |
| 027 | JavaScript ES6 | 170703T130931Z | Arnauld |
| 066 | Java | 170703T134248Z | Okx |
| 049 | Haskell | 170703T144410Z | Henry |
| 063 | Excel | 170703T143657Z | Wernisch |
| 027 | Retina | 170703T140532Z | PunPun10 |
| 046 | C# | 170703T142102Z | TheLetha |
| 007 | Japt | 170703T141241Z | Oliver |
| 024 | Pari/GP | 170703T140108Z | alephalp |
| 004 | Jelly | 170703T133133Z | Erik the |
| 041 | PHP | 170703T134434Z | Jör |
| 012 | Braingolf | 170703T133618Z | Mayube |
| 026 | Mathematica | 170703T133254Z | Martin E |
| 032 | Python 2 | 170703T130507Z | ovs |
| 008 | Brachylog | 170703T130454Z | Fatalize |
Thunno 2, 3 bytes
SḌḊ
Explanation
SḌḊ # implicit input
S # sum the digits
Ḍ # double this number
Ḋ # input is divisible by this?
# implicit output
Screenshot
Desmos, 62 bytes
f(n)=0^{mod(n,2mod(floor(n/10^{[0...floor(logn)]}),10).total)}
C++, 121 bytes
#include<iostream>
main(){std::string n;int m=0;std::cin>>n;for(char i:n){m+=i-48;};std::cout<<((stoi(n)%(m*2)==0)?0:1);}
Explanation
#include<iostream>
main(){
std::string n; int m = 0; // Initialize `n` (input) and `m` (sum)
std::cin >> n; // Get input
for(char i:n) // Loop through input to calculate the sum of digits
{
m+=i-48;
};
std::cout<<((stoi(n)%(m*2)==0)?0:1); // Output `0` if double the sum of digits is divisible by the number, else return `1`
}
Swift, 53 46 bytes
Takes in a String or Substring representing an integer in [1, 255].
{UInt8($0)!%($0.utf8.reduce(0){$0+$1-48}*2)<1}
Type information not included, since it could be either:
let f: (String) -> Bool = {UInt8($0)!%($0.utf8.reduce(0){$0+$1-48}*2)<1}
let g: (Substring) -> Bool = {UInt8($0)!%($0.utf8.reduce(0){$0+$1-48}*2)<1}
Swift Character is... weird. It's not a single byte, like in C (that's CChar), but it's also not a single Unicode codepoint (that's Unicode.Scalar). Rather, it represents an extended grapheme cluster. This makes certain oprations substantially more painful, but others substantially easier. For this reason, I access the string's utf8 property (which is a collection of UInt8).
String and Substring are collections of Character; however, they also have a lot more shared functionality than e.g. [Character] because they conform to StringProtocol, and are in fact the only types that conform to it. I thought StringProtocol would work as the input type, but then the type checker times out.
For 49 bytes, here's a version that accepts integers in [1, 2^31 - 1] or [1, 2^63 - 1] depending on the machine:
{Int($0)!%($0.utf8.reduce(0){$0+Int($1)-48}*2)<1}
Explanation/Ungolfed
{ (number: String) -> Bool in
return
UInt8(number)! // Convert String to UInt8, force-unwrap optional
% (
number.utf8 // Convert String to byte array
.reduce(0) { (prevResult: UInt8, nextChar: Character) -> UInt8 in
return prevResult + nextChar - 48
// Convert ASCII to number by subtracting 48; sum the results
} * 2
) == 0 // convert number to boolean
}
Factor + math.text.utils math.unicode, 37 bytes
[ dup 1 digit-groups Σ 2 * mod 0 = ]
Explanation
! 12
dup ! 12 12
1 digit-groups ! 12 { 2 1 }
Σ ! 12 3
2 * ! 12 6
mod ! 0
0 = ! t
Zsh, 37 bytes
for ((;i++<19;a+=2*s[i]))s=$1;((s%a))
Outputs by exit code - 0 is falsey, 1 is truthy.
Explanation:
for ((;i++<19;a+=2*s[i]))s=$1;((s%a)) # i implicitly starts at 0
s=$1; # set s to the input
for ((; )) # loop
<19; # while i is less than 19 (*)
i++ # increment i
s[i] # take the i'th character of s
2* # doubled
a+= # add to a
s%a # remainder of s divided by a
(( )) # output 0 if it's non-zero, 1 if it's zero
(*19 is the length of the maximum integer zsh can handle)
Whitespace, 103 bytes
[S S S N
_Push_0][S N
S _Duplicate_0][S N
S _Duplicate_0][T N
T T _Read_STDIN_as_integer][T T T _Retrieve_input][N
S S N
_Create_Label_LOOP][S N
S _Duplicate][N
T S S N
_If_0_Jump_to_Label_DONE][S N
S _Duplicate][S S S T S T S N
_Push_10][T S T T _Modulo][S T S S T S N
_Copy_0-based_2nd][T S S S _Add][S N
T _Swap_top_two][S S S T S T S N
_Push_10][T S T S _Integer_divide][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_DONE][T T T _Retrieve_input][S N
T _Swap_top_two][S S S T S N
_Push_2][T S S N
_Multiply]{T S T T _Modulo][T N
S T _Print_as_integer]
Letters S (space), T (tab), and N (new-line) added as highlighting only.
[..._some_action] added as explanation only.
Outputs 0 as truthy or a positive integer as falsey.
Try it online (with raw spaces, tabs and new-lines only).
To output two distinct values (0 for truthy; 1 for falsey) it would be 128 bytes instead: try it online.
Explanation in pseudo-code:
Integer sum = 0
Integer input = STDIN as integer
Integer n = input
Start LOOP:
If(n == 0):
Jump to Label DONE
Integer t = n modulo-10
sum = sum + t
n = n integer-divided by 10
Go to next iteration of LOOP
DONE:
sum = sum * 2
Integer result = input % sum
Print result as integer to STDOUT
MathGolf, 3 bytes
Σ∞÷
Explanation:
Σ # Get the digit-sum of the (implicit) input-integer
∞ # Double it
÷ # Check if the (implicit) input-integer is divisible by this value
# (after which the entire stack is output implicitly as result)
Vyxal, 3 bytes
∑dœ
Compiles as:
stack.push(summate(stack.pop()))
stack.push(stack.pop() * 2)
lhs, rhs = stack.pop(2); stack.push(int((rhs % lhs) == 0))
Explained
∑dœ
∑ # Push the sum of the integers of the input
d # Double that sum
œ # And push ((sum(input) * 2) % input) == 0
Husk, 6 5 bytes
¦DΣd¹
-1 byte from Dominic Van Essen.
The existing answer doesn't use enough builtins, and Martin Ender is inactive, so I decided to post this.
Keg+Reg, 11 bytes
Boring algorithm.
¿:;9%1+2*%
Finds the digital root of the top of the stack and then finds the remainder.
0 is a truthy value, any value that is not 0 is a falsy value. (Including ASCII characters)
Explanation (Syntactically invalid)
¿# Integer input
:# Duplicate
;9%1+# Digital Root Formula (1+(n-1)mod 9)
2*%#Multiply by 2 and find the remainder
I believe everyone here used repetition/reduction but not an existing formula.
Forth (gforth), 58 bytes
: f 0 over begin 10 /mod >r + r> ?dup 0= until 2* mod 0= ;
Code Explanation
: f \ start a new word definition
0 over \ create an accumulator and copy the input above it on the stack
begin \ start an indefinite loop
10 /mod \ divide by 10 and get quotient and remainder
>r + r> \ add remainder to accumulator
?dup \ duplicate the quotient if it's greater than 0
0= \ check if quotient is 0
until \ end the indefinite loop if it is
2* mod \ multiply result by 2, then modulo with input number
0= \ check if result is 0 (input is divisible by result)
; \ end word definition
Runic Enchantments, 11 bytes
i:'+A2*%0=@
Explanation
i: Read input, duplicate it
'+A Sum its digits
2* Multiply by 2
% Modulo input with digit sum
0= Compare to 0
@ Print and terminate
Befunge-93, 34 bytes
p&::v>0g2*%.@
+19:_^#:/+91p00+g00%
Prints 0 for truthy, a different integer for falsey.
Brachylog, 7 bytes
f.&ẹj+∈
The predicate succeeds if the input is divisible by twice the sum of its digits, and fails otherwise. Run as a program, success prints true. and failure prints false..
This started off as a minor edit to Fatalize's answer, golfing a byte off by replacing +×₂ with j+, but as I was testing it I noticed that one or another of the updates he's made to the language in the last year and a half seems to have broken his solution on the case of 18, with I apparently being unable to assume the value of 1, so I ended up having to restructure it somewhat (fortunately without changing the byte count).
f. The output variable is a list of the input's factors.
& And,
ẹ the digits of the input,
j all duplicated,
+ sum up to
∈ a member of the output variable.
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
Pyth - 12 Bytes
%sZ*2ssMscZ1
Explanation:
% - implicitly print modulus of
s - parse int
Z - input
* - two times
s - sum of
M - map
s - parse int to
c - substrings
Z - of input
1 - of length 1
Deorst, 16 bytes
iE"E|miEH:+zE|%N
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]
Java 7, 197 133 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));}
Ly, 10 bytes
nsS&+2*lf%
Ly is lucky enough to have a splitting built-in.
Returns 0 for truthy and a number greater than 0 for falsy.
><>, 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.
Add++, 11 bytes
L,EDEs;A@%!
First time I've used either a Lambda or ; in an Add++ answer
How it works
L, - Create a lambda function. Example argument; 172
ED - Push the digits; STACK = [[1 7 2]]
Es - Stack-clean sum; STACK = [10]
; - Double; STACK = [20]
A - Push the argument; STACK = [20 172]
@% - Modulo; STACK = [12]
! - Logical NOT; STACK = [0]
K (oK), 14 bytes
Solution:
(2*+/48!$x)!x:
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.
Neim, 3 bytes
𝐬ᚫ𝕞
Explanation:
𝐬 Implicitly convert to int array and sum the digits
ᚫ Double
𝕞 Is it a divisor of the input?
C# (.NET Core), 51 bytes
n=>{int l=n,k=0;for(;l>0;l/=10)k+=l%10;return n%k;}
0 for truthy, anything else for falsey.
Java (OpenJDK 8), 40 bytes
i->i%(i+"").chars().map(k->k*2-96).sum()
Returns 0 as truthy value and a value greater than 0 as falsy value.
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.
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.
TI-BASIC, 27 26 21 bytes
-5 thanks to @Oki
:fPart(Ans/sum(2int(10fPart(Ans10^(~randIntNoRep(1,1+int(log(Ans
This is made trickier by the fact that there is no concise way to sum integer digits in TI-BASIC. Returns 0 for True, and a different number for False.
Explanation:
:fPart(Ans/sum(2int(10fPart(Ans10^(-randIntNoRep(1,1+int(log(Ans
10^(-randIntNoRep(1,1+int(log(Ans #Create a list of negative powers of ten, based off the length of the input, i.e. {1,0.1,0.01}
Ans #Scalar multiply the input into the list
10fPart( #Remove everything left of the decimal point and multiply by 10
2int( #Remove everything right of the decimal point and multiply by 2
sum( #Sum the resulting list
Ans/ #Divide the input by the sum
:fPart( #Remove everything left of the decimal, implicit print
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
APL, 13 bytes
{⍵|⍨2×+/⍎¨⍕⍵}
Outputs 0 as a truthy value, and any other as falsy.
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.
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
Mini-Flak, 296 292 bytes
({}((()[()]))){(({}[((((()()()){}){}){}){}])({}(((({})){}){}{}){})[({})])(({}({})))({}(({}[{}]))[{}])({}[({})](({}{})(({}({})))({}(({}[{}]))[{}])({}[({})]))[{}])(({}({})))({}(({}[{}]))[{}])({}[({})])}{}({}(((({}){})))[{}]){({}((({}[()]))([{(({})[{}])()}{}]()){{}{}(({}))(()[()])}{})[{}][()])}
The TIO link have more comments from me, so it is partially easier to read.
Truthy/Falsey: Truthy (divisible) if the second number is equal to the third number, falsy otherwise. So both the truthy and falsy set are infinite, but I suppose that should be allowed. +10 byte if that is not.
Note: Leading/trailing newlines/whitespaces are not allowed in input.
x86-64 Machine Code, 24 bytes
6A 0A 5E 31 C9 89 F8 99 F7 F6 01 D1 85 C0 75 F7 8D 04 09 99 F7 F7 92 C3
The above code defines a function in 64-bit x86 machine code that determines whether the input value is divisible by double the sum of its digits. The function conforms to the System V AMD64 calling convention, so that it is callable from virtually any language, just as if it were a C function.
It takes a single parameter as input via the EDI register, as per the calling convention, which is the integer to test. (This is assumed to be a positive integer, consistent with the challenge rules, and is required for the CDQ instruction we use to work correctly.)
It returns its result in the EAX register, again, as per the calling convention. The result will be 0 if the input value was divisible by the sum of its digits, and non-zero otherwise. (Basically, an inverse Boolean, exactly like the example given in the challenge rules.)
Its C prototype would be:
int DivisibleByDoubleSumOfDigits(int value);
Here are the ungolfed assembly language instructions, annotated with a brief explanation of the purpose of each instruction:
; EDI == input value
DivisibleByDoubleSumOfDigits:
push 10
pop rsi ; ESI <= 10
xor ecx, ecx ; ECX <= 0
mov eax, edi ; EAX <= EDI (make copy of input)
SumDigits:
cdq ; EDX <= 0
div esi ; EDX:EAX / 10
add ecx, edx ; ECX += remainder (EDX)
test eax, eax
jnz SumDigits ; loop while EAX != 0
lea eax, [rcx+rcx] ; EAX <= (ECX * 2)
cdq ; EDX <= 0
div edi ; EDX:EAX / input
xchg edx, eax ; put remainder (EDX) in EAX
ret ; return, with result in EAX
In the first block, we do some preliminary initialization of registers:
PUSH+POPinstructions are used as a slow but short way to initializeESIto 10. This is necessary because theDIVinstruction on x86 requires a register operand. (There is no form that divides by an immediate value of, say, 10.)XORis used as a short and fast way to clear theECXregister. This register will serve as the "accumulator" inside of the upcoming loop.- Finally, a copy of the input value (from
EDI) is made, and stored inEAX, which will be clobbered as we go through the loop.
Then, we start looping and summing the digits in the input value. This is based on the x86 DIV instruction, which divides EDX:EAX by its operand, and returns the quotient in EAX and the remainder in EDX. What we'll do here is divide the input value by 10, such that the remainder is the digit in the last place (which we'll add to our accumulator register, ECX), and the quotient is the remaining digits.
- The
CDQinstruction is a short way of settingEDXto 0. It actually sign-extends the value inEAXtoEDX:EAX, which is whatDIVuses as the dividend. We don't actually need sign-extension here, because the input value is unsigned, butCDQis 1 byte, as opposed to usingXORto clearEDX, which would be 2 bytes. - Then we
DIVideEDX:EAXbyESI(10). - The remainder (
EDX) is added to the accumulator (ECX). - The
EAXregister (the quotient) is tested to see if it is equal to 0. If so, we have made it through all of the digits and we fall through. If not, we still have more digits to sum, so we go back to the top of the loop.
Finally, after the loop is finished, we implement number % ((sum_of_digits)*2):
The
LEAinstruction is used as a short way to multiplyECXby 2 (or, equivalently, addECXto itself), and store the result in a different register (in this case,EAX).(We could also have done
add ecx, ecx+xchg ecx, eax; both are 3 bytes, but theLEAinstruction is faster and more typical.)Then, we do a
CDQagain to prepare for division. BecauseEAXwill be positive (i.e., unsigned), this has the effect of zeroingEDX, just as before.Next is the division, this time dividing
EDX:EAXby the input value (an unmolested copy of which still resides inEDI). This is equivalent to modulo, with the remainder inEDX. (The quotient is also put inEAX, but we don't need it.)Finally, we
XCHG(exchange) the contents ofEAXandEDX. Normally, you would do aMOVhere, butXCHGis only 1 byte (albeit slower). BecauseEDXcontains the remainder after the division, it will be 0 if the value was evenly divisible or non-zero otherwise. Thus, when weRETurn,EAX(the result) is 0 if the input value was divisible by double the sum of its digits, or non-zero otherwise.
Hopefully that suffices for an explanation.
This isn't the shortest entry, but hey, it looks like it beats almost all of the non-golfing languages! :-)
C89, 55 53 bytes
(Thanks to Steadybox!
s,t;f(x){for(t=x,s=0;t;t/=10)s+=t%10;return x%(s*2);}
It takes a single input, x, which is the value to test. It returns 0 if x is evenly divisible by double the sum of its digits, or non-zero otherwise.
Ungolfed:
/* int */ s, t;
/*int */ f(/* int */ x)
{
for (t = x, s = 0; t /* != 0 */; t /= 10)
s += (t % 10);
return x % (s * 2);
}
As you can see, this takes advantage of C89's implicit-int rules. The global variables s and t are implicitly declared as ints. (They're also implicitly initialized to 0 because they are globals, but we can't take advantage of this if we want the function to be callable multiple times.)
Similarly, the function, f, takes a single parameter, x, which is implicitly an int, and it returns an int.
The code inside of the function is fairly straightforward, although the for loop will look awfully strange if you're unfamiliar with the syntax. Basically, a for loop header in C contains three parts:
for (initialization; loop condition; increment)
In the "initialization" section, we've initialized our global variables. This will run once, before the loop is entered.
In the "loop condition" section, we've specified on what condition the loop should continue. This much should be obvious.
In the "increment" section, we've basically put arbitrary code, since this will run at the end of every loop.
The larger purpose of the loop is to iterate through each digit in the input value, adding them to s. Finally, after the loop has finished, s is doubled and taken modulo x to see if it is evenly divisible. (A better, more detailed explanation of the logic here can be found in my other answer, on which this one is based.)
Human-readable version:
int f(int x)
{
int temp = x;
int sum = 0;
while (temp > 0)
{
sum += temp % 10;
temp /= 10;
}
return x % (sum * 2);
}
Python 3, 35 bytes
lambda a:a%(sum(map(int,str(a)))*2)
Java (OpenJDK 8), 55 53 bytes
a->{int i=0,x=a;for(;x>0;x/=10)i+=x%10*2;return a%i;}
A return value of 0 means truthy, anything else means falsy.
Since my comment in Okx's answer made no ripple, I deleted it and posted it as this answer, golfed even a bit more.
Further golfing thanks to @KrzysztofCichocki and @Laikoni who rightfully showed me I needn't answer a truthy/falsy value, but any value as long as I describe the result.
PHP, 44 bytes
for(;~$d=$argn[$i++];)$t+=2*$d;echo$argn%$t;
Run like this:
echo 80 | php -nR 'for(;~$d=$argn[$i++];)$t+=2*$d;echo$argn%$t;'
Explanation
Iterates over the digits to compute the total, then outputs the modulo like most answers.
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
Haskell, 38 37 42 bytes
Thanks to Zgarb for golfing off 1 byte
f x=read x`mod`foldr((+).(*2).read.pure)0x
Takes input as a string; returns 0 if divisible and nonzero otherwise.
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
Haskell, 35 34 bytes
f x=mod x$2*sum[read[c]|c<-show x]
Returns '0' in the true case, the remainder otherwise.
Haskell, pointfree edition by nimi, 34 bytes
mod<*>(2*).sum.map(read.pure).show
Alice, 16 bytes
/o. &
\i@h /+.+F
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.
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)
05AB1E, 5 4 bytes
-1 byte thanks to Okx
SO·Ö
You can also remove the last Ö to get 0 for truthy and something else for falsy resulting in only 3 bytes but to me that just doesn't seem to appropriately fit the definition.
Explanation
SO·Ö
SO # Separate the digits and sum them
· # Multiply the result by two
Ö # Is the input divisible by the result?
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.
Try it online! Or verify all test cases.
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
Perl 5, 27 bytes
$_%(2*eval join'+',split//)
Returns 0 for Truthy and non-zero for Falsy
Bash + coreutils + bc, 46 bytes
yes $1%\(0`echo $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.
PowerShell, 39 bytes
($a="$args")%($a*2-replace'\B','+'|iex)
0 as Truthy output, any other number as Falsey.
PS D:\> D:\t.ps1 80
0
PS D:\> D:\t.ps1 81
9
It takes the args array as a string, does string multiplication to double all the digits, regex-replaces non-word-boundaries to make '8+0+8+0', eval's that to get the sum, and calculates a remainder of original/sum.
Husk, 9 8 bytes
Thanks to Leo for saving 1 byte.
Ṡ¦ȯ*2ṁis
Explanation
Ṡ¦ȯ Test whether f(x) divides x, where f is the function obtained by
composing the next 4 functions.
s Convert x to a string.
ṁi Convert each character to an integer and sum the result.
*2 Double the result.
Japt, 7 4 bytes
Takes input as a string. Outputs 0 for true or a number greater than 0 for false, which, from other solutions, would appear to be valid. If not, let me know and I'll rollback.
%²¬x
Explanation
Implicit input of string U."390"
²
Repeat U twice."390390"
¬
Split to array of individual characters.["3","9","0","3","9","0"]
x
Reduce by summing, automatically casting each character to an integer in the process.24
%
Get the remainder of dividing U by the result, also automatically casting U to an integer in the process. Implicitly output the resulting integer.6 (=false)
J, 15 bytes
0 indicates truthy, nonzero indicates falsy.
|~[:+/2#"."0@":
Explanation
"."0@": convert to list of digits
[:+/2# sum 2 copies of the list ([: forces monadic phrase)
|~ residue of sum divided by argument?
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
MATL, 7 bytes
tV!UsE\
Outputs 0 if divisible, positive integer otherwise. Specifically, it outputs the remainder of dividing the number by twice the sum of its digits.
Explanation
t % Implicit input. Duplicate
V!U % Convert to string, transpose, convert to number: gives column vector of digits
s % Sum
E % Times 2
\ % Modulus. Implicit display
JavaScript (ES6), 31 29 27 bytes
Takes input as a string. Returns zero for truthy and non-zero for falsy.
n=>n%eval([...n+n].join`+`)
Commented
n => n % eval([...n + n].join`+`)
n => // take input string n -> e.g. "80"
n + n // double the input -> "8080"
[... ] // split -> ["8", "0", "8", "0"]
.join`+` // join with '+' -> "8+0+8+0"
eval( ) // evaluate as JS -> 16
n % // compute n % result -> 80 % 16 -> 0
Test cases
let f =
n=>n%eval([...n+n].join`+`)
console.log('[Truthy]');
console.log(f("80"))
console.log(f("100"))
console.log(f("60"))
console.log(f("18"))
console.log(f("12"))
console.log('[Falsy]');
console.log(f("4"))
console.log(f("8"))
console.log(f("16"))
console.log(f("21"))
console.log(f("78"))
console.log(f("110"))
console.log(f("111"))
console.log(f("390"))
Java, 66 bytes
-1 byte thanks to Olivier
a->{int i=0;for(int b:(""+a).getBytes())i+=b-48;return a%(i*2)<1;}
Ungolfed & explanation:
a -> {
int i = 0;
for(int b : (""+a).getBytes()) { // Loop through each byte of the input converted to a string
i += b-48; // Subtract 48 from the byte and add it to i
}
return a % (i*2) < 1 // Check if a % (i*2) is equal to one
// I use <1 here for golfing, as the result of a modulus operation should never be less than 0
}
Excel, 63 bytes
=MOD(A1,2*SUMPRODUCT(--MID(A1,ROW(OFFSET(A$1,,,LEN(A1))),1)))=0
Summing digits is the lengthy bit.
Retina, 38 27 bytes
-11 bytes and fixed an error with the code thanks to @MartinEnder
$
$_¶$_
.+$|.
$*
^(.+)¶\1+$
Prints 1 if divisible, 0 otherwise
Explanation (hope I got this right)
$
$_¶$_
Appends the entire input, plus a newline, plus the input again
.+$|.
$*
Converts each match to unary (either the entire second line which is the original input, or each digit in the first line)
^(.+)¶\1+$
Check if the first line (the doubled digit sum) is a divisor of the second line
C#, 46 bytes
using System.Linq;n=>n%(n+"").Sum(c=>c-48)*2<1
Full/Formatted version:
using System;
using System.Linq;
class P
{
static void Main()
{
Func<int, bool> f = n => n % (n + "").Sum(c => c - 48) * 2 < 1;
Console.WriteLine(f(80));
Console.WriteLine(f(100));
Console.WriteLine(f(60));
Console.WriteLine();
Console.WriteLine(f(16));
Console.WriteLine(f(78));
Console.WriteLine(f(390));
Console.ReadLine();
}
}
Japt, 7 bytes
vUì x*2
Returns 1 for true, 0 for false
Explanation
vUì x*2
v // Return 1 if the input is divisible by:
Uì // Input split into a base-10 array
x // Sum the array
*2 // While mapped by *2
Jelly, 4 bytes
DSḤḍ
Explanation:
DSḤḍ Takes an integer as input.
D Get digits (convert to base 10)
S Sum
Ḥ Unhalve (double)
ḍ Check if y (the input itself) is divisible by x
PHP, 41 bytes
prints zero if divisible, positive integer otherwise.
<?=$argn%(2*array_sum(str_split($argn)));
Braingolf, 13 12 bytes
VR.Mvd&+2*c%
Outputs 0 for truthy, any other number for falsey.
Explanation
VR.Mvd&+2*c% Implicit input from command-line args
VR Create stack2, return to stack1
.M Duplicate input to stack2
vd Switch to stack2, split into digits
&+ Sum up all digits
2* Double
c Collapse stack2 back into stack1
% Modulus
Implicit output of last item on stack
Mathematica, 26 bytes
(2Tr@IntegerDigits@#)∣#&
No clue why ∣ has a higher precedence than multiplication...
Brachylog, 8 bytes
ẹ+×₂;I×?
Explanation
ẹ+ Sum the digits
×₂ Double
;I×? There is an integer I such that I×(double of the sum) = Input
