text:
Is a number divisible by each of its digits?
My friend and I were working on a lab in our AP Computer Science class and decided to code golf one one the problems since we still had half the class free after we finished. Here is the question:

Given a number n, is n divisible by each of its digits?

For example, 128 will pass this test- it is divisible by 1,2, and 8. Any numbers with a zero automatically disqualify the number. While you may use other languages and post solutions with them if you like, we are most interested in seeing how compact people can make the program in Java, as that is the language we use in the class. So far, we both have 51. Here is my current code:
public boolean dividesSelf(int n){for(int p=n;n%10>0;)n/=p%(n%10)>0?.1:10;return n<1;}
// 51 characters

// Breakdown:
// for(int p=n;         Saves one semicolon to put declaration into for loop
// n%10>0;)             Basic check-for-zero
// n/=                  Pretty simple, discarding one number off of n at a time
// p%(n%10)>0?          If p (the given value) is not divisible by n%10 (the current digit)...
// .1:10;               Divide by .1 (multiply by 10) so it fails the check next iteration. If it is divisible, divide by 10 to truncate the last digit
// return n<1           If the number was fully divisible, every digit would be truncated, and n would be 0. Else, there would still be non-zero digits.

Requirements
The method signature can be whatever you want. Just count the function body. Make sure, though, that the method returns a boolean value and only passes in one numeric parameter (not a string).
The code must be able to pass all of these cases (in order to stay true to the directions of the original question, only boolean true and false values count if the language supports booleans. If and only if your language does not have boolean variables you may represent false with 0 and true with any nonzero integer (preferably 1 or -1):
128 -> true
 12 -> true
120 -> false
122 -> true
 13 -> false
 32 -> false
 22 -> true
 42 -> false
212 -> true
213 -> false
162 -> true
204 -> false

Also, we didn't count whitespace, so feel free to do the same, unless the whitespace is essential to the working of the program (so newlines in Java don't count, but a single space between int and x=1 does count.)
Good luck!

Welcome to PPCG! A few suggestions: 1. Not counting functional whitespace is a bad idea. Any answer written in Whitespace will automatically win. 2. Should our submission print/return true and false or are truthy/falsy values OK as well? 3. The java tag doesn't really apply here, as the challenge itself is unrelated to Java.

Okay. sorry for the issues. Just to clear it up, would you consider the space in 'int p=n' to be functional, because I did not previously. I will fix the other issues you pointed out.

All whitespace required for the code to work is functional.

Okay, thanks for the response!

Just count the calculation inside the brackets - does this apply to all languages that can define functions?

Yes, only count the code that is actually doing work, so ignore anything that defines the function but does not contribute to the actual implementation. Hopefully that clears it up.

Note that 0 is a multiple of 0, which makes me wonder how the answers would change if you didn't specifically exclude that.

One parameter, ok, but string type or numeric?

Numeric inputs only.

@RickyDemer: since 0 would be an exceptional input in that case (it's the only number with 0 digits that is a multiple of each of them), I imagine most answers would just get longer in an uninteresting way to include a check for it. So I like the problem as posed by the title better (divisible by its digits, rather than being a multiple of its digits, which excludes 0).

I'm tempted to suggest the alternate interpretation of the question, in which dividing 123412341234 by 3 yields [12, 412, 412, 4].

Found an OEIS sequence for this: A034838

Perl 6, 13
sub golf($_) {
   $_%%.comb.all
}

Uses the implicit variable $_ — $_ %% .comb.all is equivalent to $_ %% all($_.comb). %% is the "is divisible" operator, and comb with no additional argument returns a list of the characters in a string. As an example, if the argument is 123, then the function evaluates
123 %% all(123.comb)

which is
123 %% all(1, 2, 3)

junction autothreading makes it
all(123 %% 1, 123 %% 2, 123 %% 3)

which is
all(True, False, True)

which is false in boolean context because it's an "all" junction and clearly not all of its elements are true.
It should be possible to coerce the return value to Bool and hide the junction-ness from callers by making the function signature sub golf($_ --> Bool()), but coercions in function signatures don't work yet in Rakudo. The return value is still correctly true or false, it's just not True or False.

If you want to make it return a Bool just add so to the front of the code so$_%%.comb.all.

C# and System.Linq - 26 / 40
Per the rules, not counting the method declaration itself.
bool dividesSelf(int i) {
    return(i+"").All(d=>i%(d-48d)<1);
}

Showing that once again, C# is the superior choice when Java is under consideration... I kid, I kid!
Unfortunately, this function (and many in other answers) will not produce correct results for negative input. We can fix this, but the solution loses a lot of its charm (and grows to 46 characters in length):
return(i+"").All(d=>d>48&&i%(d-48)==0||d==45);

Edit: shaved off one character with Tim's suggestion.
Edit: with the introduction of expression-bodied members in C# 6, we can pare this down further by cutting out the return:
bool dividesSelf(int i) =>
    (i+"").All(d=>i%(d-48d)<1);

for a total of 26 characters (in my opinion, the => should not be included any more than braces would be). The version handling negative numbers can be similarly shortened.

Why .0? There's no need for anything other than integer modulus.

@PeterTaylor: There is if you want the shortest program -- i % 0 with i an integer gives a DivideByZeroException.

And with a double it gives NaN! Nice!

48d is the same as 48.0, but one less character (d for double).

Nice solution... good to see someone finally bring it with C#

@JeroenMostert :) hehe well that'll teach me to blurt out stuff without checking myself. (eh, probably not, seems i've learned that particular lesson about 1,000 times.) tks for the response. i have deleted my comment so that it wouldn't be there to confuse the issue if someone didn't read further.

Are you allowed to use lambda syntax to get rid of the pesky return and trailing semi-colon? i.e. Func<int, bool> dividesSelf = (i) => (i+"").All(d=>i%(d-48d)<1). In the negative case, you perhaps could use the non short circuit version of& vs && :)

@StuartLC: lambdas aren't methods; their scope is different, so I think that's bending the rules too far. But since C# 6 (which this answer predates), we have expression-bodied members, which do allow us to shorten the definition. For the negative case, we can't use &, precisely because & doesn't short-circuit -- you'll get a divide by zero exception on the %. We can fix that by making it a double (with d), but then we've lost one character again.

Good point :) One day we'll hopefully not need explicit return keyword and possibly also allow for functional return type inference, to bring us inline with other functional languages.

APL (13 11) (apparently the brackets don't count)
{0∧.=⍵|⍨⍎¨⍕⍵}

Explanation:

⍎¨⍕⍵: evaluate each character in the string representation of ⍵
⍵|⍨: for each of those, find the modulo of it and ⍵
0∧.=: see whether all of those are equal to 0

Testcases:
      N,[.5] {0∧.=⍵|⍨⍎¨⍕⍵} ¨ N←128 12 120 122 13 32 22 42 212 213 162 204
128 12 120 122 13 32 22 42 212 213 162 204
  1  1   0   1  0  0  1  0   1   0   1   0

APL can do X%0 ? without throwing ?

@Optimizer: yes. 0|X gives X.

Sweet. Also your answer is 11 bytes, not 13

Also, you are using 4 bytes in the final computation. Do you have a sum of array method ? If yes, do that and Boolean not it.

@optimizer: That doesn't work in APL. Boolean not (~) expects an actual boolean value (0/1) and will give a DOMAIN ERROR if given something else. You could do ~×+/ (not of sign of sum) but that's also 4 bytes.

Only APL would not give an error on modulo by 0, and crash on evaluating a non-bool as a bool ;)

One character shorter with a train instead of dfn: (0∧.=⍎¨∘⍕|⊢)

Python 2: 43 chars
f=lambda n:any(n%(int(d)or.3)for d in`n`)<1

Checks whether the number has any nonzero remainders modulo its digits, and outputs the negation of that. Zero digits are handled strangely: since computing %0 causes an error, digits of 0 are replaced with .3, which seems to always give a nonzero result due to floating point inaccuracies.
The function body is 32 chars.

Perl - 27 bytes
sub dividesSelf{
    $_=pop;s/./!$&||$_%$&/ger<1
}

Not counting the function signature, as instructed.
Sample Usage:
use Data::Dump qw(dump);
for $i (128, 12, 120, 122, 13, 32, 22, 42, 212, 213, 162, 204) {
  printf "%3d -> %s\n", $i, dump(dividesSelf $i);
}

Sample Output:
128 -> 1
 12 -> 1
120 -> ""
122 -> 1
 13 -> ""
 32 -> ""
 22 -> 1
 42 -> ""
212 -> 1
213 -> ""
162 -> 1
204 -> ""

Addressing the problem specification: "Only boolean true and false values count. Truthy/falsey values do not count."
use Data::Dump qw(dump);
dump(1 == 1);
dump(0 == 1);

Outputs:
1
""

'True' and 'False' are defined as 1 and "".
Erratum:
As Brad Gilbert rightly points out, perl defines true as a scalar which is both the integer 1 and the string "1" simultaneously, and false as a scalar which is both the integer 0 and the string "" simultaneously.

This can be shortened by not using $_: pop=~s///ger<1. I don't know whether the OP will agree that 1 and "" are valid results. If not, then it can be fixed with two more bytes: just add |0.

perl -pe'$_=s/./!$&||$_%$&/ger<1|0' is 26 bytes including the |0 and -p flag. You don't have to use a function.

@hvd the inner logic contains $_ as well. Using "@_" in both places is one byte longer.

@chilemagic this reads from STDIN and writes to STDOUT, rather than being a function as requested. I was tempted to include my($n)=@_; as part of the 'method signature', but it seems a bit of a stretch.

I can't link to a comment, but op's comment on this answer says it is okay if it isn't a function. I guess it is unclear whether STDIN to STDOUT is allowed.

@primo Oops, you're right. I did test before commenting, but the way I tested was wrong: I was calling the sub in a loop with $_. Sorry about that. Normally I'd delete my earlier comment, but the part about |0 may still make it worth leaving up.

Actually the True and False values are more like dualvar(1,'1') and dualvar(0,'').

@BradGilbert That is interesting. I am reasonably familiar with perlguts, but I wasn't aware that true and false were special cased. They're actually 'triple scalars', marked as SVIV (int), SVNV (double), and SVPV (string).

Actually the first time you use a string as a number or a number as a string, the variable gets modified to hold that additional data. That is why you only get a warning the first time you use 'abc' as a number (assuming you have use warnings; enabled. )

@BradGilbert Indeed: http://codepad.org/9VszodfA

JavaScript ES6, 39 32 28 bytes
v=>[...""+v].every(x=>v%x<1)

Thanks core1024 for the suggestion to replace (""+v).split("") with [...""+v], and openorclose for suggesting the use of every function.
The answer currently doesn't contain one bit of my code :O
Previous solution
v=>[...""+v].filter(x=>v%x|!+x)==""

=="" is not a valid way to check if an array is empty, since [""]=="" returns true, but the array is guarantee to contain non-empty string, so it works here.
The rest are quite standard shorthand type conversion in JavaScript.

You can save some characteras by replacing (""+v).split("") with [...""+v].

Why not use the every method? v=>[...""+v].every(x=>v%x<1);

@openorclose: Thanks. Never had a chance to use it in JS, so I never thought of searching for such function.

v=>![...""+v].some(x=>v%x)

@l4m2 Since v%0 returns NaN and NaN == false, so in your case numbers that contains 0, such as 10, may return true.

Btw shouldn't the answer be 28 bytes long?

@user71546: Fixed the character count.

CJam, 11 10 bytes
{
    _Ab:df%:+!
}:F;

This defines a function named F and discards the block from the stack.
Try it online.
Test cases
$ cjam <(echo '{_Ab:df%:+!}:F;[128 12 120 122 13 32 22 42 212 213 162 204]{F}%p')
[1 1 0 1 0 0 1 0 1 0 1 0]

How it works
_      " Copy the integer on the stack.                                          ";
Ab     " Push the array of its digits in base 10.                                ";
:d     " Cast each digit to Double.                                              ";
f%     " Take the integer on the stack modulus each of its digits.               ";
:+     " Add the results.                                                        ";
!      " Push the logical NOT of the sum.                                        ";

Did CJam have the features you used for the 10-byte solution when the question was written?

@ThomasKwa: Yes it did. I've tested the code in version 0.6.2, which was released in July 2014.

Java 8, 46 Bytes (method body)
Using Jeroen Mostert's converting to double trick.
public static boolean dividesSelf(int n) {
    return(""+n).chars().allMatch(x->n%(x-48d)<1);
}

Pyth, 12 bytes
!f|!vT%vzvTz

This filters the characters in the string for being either zero (!vT) or not dividing the input (%vzvT), then takes the logical not of the resulting list.
Try it here.

No, I'm fine if a function is not used. I just wanted to point out to anybody that was using functions that they do not need to count the declaration, and only the code inside.

Ruby, 44 bytes (function body: 37)
Probably has potential to be golfed further.
f=->n{n.to_s.chars.all?{|x|x>?0&&n%x.hex<1}}

Input taken through function f. Example usage:
f[128] # => true
f[12]  # => true
f[120] # => false
...

You can change .to_i to .hex, since single-digit numbers are the same in base 16, and can change ==0 to <1.

Python - 59 50 49 47 bytes
f=lambda n:all(c>'0'and 0==n%int(c)for c in`n`)

I'm sure there's a faster way... oh well.
Edit - Thanks to FryAmTheEggman for the golfing tips.
Edit 2 - FryAmTheEggman may as well have written this at this point, oops
Edit 3 - Hands up if you didn't even know genexps were a thing. ...Just me?

Oh, thanks a lot! I keep forgetting about all those things. (I also didn't realize you could less-than chars in that way.)

Oh, flipping the logic also seems to shorten it a bit: f=lambda n:all([c>'0'and 0==n%int(c)for c in\n`])`. And no problem :)

Oh, I didn't realize there even was an all method.

Would 1>n%int(c) work?

Why a list-comprehension? Using a genexp: all(c>'0'and 0==n%int(c)for c in`n`) does exactly the same, with 2 char less and even saving the allocation of the list.

Pyth 11
!f%Q|vT.3`Q

This combines @isaacg's and @xnor's answers. It filters out digits from the input by checking the value of input % (eval(current_digit) or .3). Then it checks if the resulting string is empty or not.
Came across another couple same-length variants:
!f%Q|T.3jQT
!f|!T%QTjQT

Try it online.

Bash + coreutils, 44 bytes
The full function definition is:
f()((`tr 0-9 \10<<<$1``sed "s/./||$1%&/g"<<<$1`))

I'm not sure how to score this as normally shell functions use a single set of {} or () to contain the function body.  I found here I could also use double (()) to contain the function body which causes an arithmetic expansion which is what I need here.  So for now I am counting just one pair of those brackets - further discussion of this is welcome.
Output:
$ for i in 128 12 120 122 13 32 22 42 212 213 162 204; do f $i; printf "%d " $?; done
1 1 0 1 0 0 1 0 1 0 1 0 $
$

Uh - its not clear to me whether 1s and 0s are acceptable or if I have to print true/false?

J - 14 char
The function body is the portion after the =:. If we want to minimize the character count for the whole function, that's the 15 char */@(0=,.&.":|]).
f=:0*/@:=,.&.":|]

,.&.": is the shortest way in J to expand as number into a list of its decimal digits: convert to string, separate the digits, and convert each digit back into a number. ,.&.":|] takes the input number (]) modulo (|) those digits. 0*/@:= returns true if all the results were 0, else gives a false.
   f 162
1
   f every 204 212 213
0 1 0

Java - 121 102 97 79 78 bytes
I just know this will get clobbered later. Oh well.
boolean b(int a){int m=10,j,t=1;for(;m<a*10;m*=10){j=10*(a%m)/m;if(j==0||a%j>0)t=0;}return t>0;}

I'll be back.

You can now name your function whatever you want. I changed the rules so you only count the calculations inside the actual function, but the function must return a boolean type. So that is currently at 86 characters.

Haskell - 100 54 38
f x=all(\y->y>'0'&&x`mod`read[y]<1)$show x

Still learning, critiques appreciated

I had a comment here, but I accidentally deleted it somehow... Anyway, some suggestions:

Drop the lengths, they are unnecessary.
Replace t by its definition.
elem y s is unnecessary.
/='0' can be moved to the left filter, in place of elem y s.
In this case, /='0' is equivalent to >'0', since every letter is a digit.
Put mod in backticks, so it becomes infix.
Put everything on a single line.

1 and 3 were from when I was trying to do it a different way and salvaged code. Thanks for the tips.

my suggestions: instead of using s==filter(...)s you should use all(...)s. now, because s only appears once in the expression, you can replace it with it's definition and drop where. also, instead of ==0 you could use <1.

great improvement from the first version!

I think you can still lose one byte if you replace all(\y->...)$show x by and[...|y<-show x].

You actually gain a byte. and[y|y<-show x,y>'0'&&x\mod`read[y]<1]`

Julia 32 25 23
Improved using digits
Also fixes problem with negative numbers
selfDivides(x)=sum(x%digits(x).^1.)==0

Old method
All digits divide if the sum of all the remainders is 0.  Like others, has a problem with negative numbers.
selfDivides(x)=sum(x.%(Float64["$x"...]-48))==0

Output
[selfDivides(x) for x in [128,12,120,122,13,32,22,42,212,213,162,204]]
12-element Array{Any,1}:
  true
  true
 false
  true
 false
 false
  true
 false
  true
 false
  true
 false

Improved method also handles BigInt
selfDivides(BigInt(11111111111111111111111111111111111111112))
true

however
selfDivides(BigInt(11111111111111111111111111111111111111113))
false

because
BigInt(11111111111111111111111111111111111111113) %3
1

it is for a very old julia (0.4 i think), here is an actualized 23 bytes version: selfDivides(x)=sum(x.%digits(x).^1.)<1

05AB1E (legacy), 3 bytes
SÖP

Only 1 is truthy in 05AB1E, so this will output 1 if the input-integer is divisible by each of its digits.
For falsey test cases it either outputs 0, or a multiple of the input if it contains 0s (due to division by zero errors). If you want a distinct falsey output of 0, you can add a trailing Θ (== 1 builtin).
Try it online or verify all test cases.
Explanation:
S    # Convert the (implicit) input-integer to a list of digits
 Ö   # Check for each digit if it evenly divides the (implicit) input-integer
     # (results in 1 for truthy; 0 for falsey; and itself for division by zero errors)
  P  # Take the product of this list to check if all are truthy
     # (after which it is output implicitly as result)

R: 72 67 65
The function
f<-function(a)!(anyNA(a%%(d=as.double(strsplit(paste0(a),"")[[1]])))|sum(a%%d))

Thanks to @AlexA and @plannapus for the savings
Test run
i=c(128,12,120,122,13,32,22,42,212,213,162,204)
for(a in i){print(f(a))}
[1] TRUE
[1] TRUE
[1] FALSE
[1] TRUE
[1] FALSE
[1] FALSE
[1] TRUE
[1] FALSE
[1] TRUE
[1] FALSE
[1] TRUE
[1] FALSE

I count 70 bytes in your function body currently, not 72. But you can get it down to 67 using d=as.double(strsplit(toString(a),"")[[1]]);!(anyNA(a%%d)|sum(a%%d)). :)

@AlexA. Thanks.  One of my first attempts wih R.  Will definitely revisit:)

@MickyT paste(a) instead of toString(a) gives the same result.

@plannapus Thanks, neat little trick.  Must remember that

CJam, 15 bytes
{_Abf{_{%}1?}1b!}

{} is the closest thing to a function in CJam. I am just counting the body of the function
Use it like this:
128{_Abf{_{%}1?}1b!}~

To get either 1 (if the number is divisible) or 0 (if the number is not divisible by its digits).
Try it online here
Explanation
_Ab                "Copy the number and split it to its digits";
   f{      }       "For each digit, run this code block on the number";
     _{%}1?        "If the digit is 0, put 1, otherwise perform number modulus digit";
            1b     "We now have an array of modulus corresponding to each digit. Sum it up";
              !    "Negate the sum. If all digits were divisible, sum of modules will be"
                   "0, thus answer should be 1 and vice versa";

I might be missing something, but after quickly reading up on CJam, some things seems to not make sense: how does Ab split the digits? It seems to just convert it to base 10. Also, how does % know to mod by the number, and not just the next digit, since it seems that the next digit would be next on the stack?

Answering all your question will be tricky. It would be super easy to learn by putting ed after each character in the code. Try running 128{ed_edAedbedf{ed_ed{ed%ed}1ed?ed}ed1edbed!ed}~

Answers to particular questions : doing base 10 gives an array of base 10 converted numbers, which are the digits themselves in this case. % simply take the last two numbers (in this case) and calculate the mod. Last two numbers here are the actual number and digit (always)

Okay, thanks for the advice!

C89, 43 bytes
unsigned char d(int n, int c) {
        int a=n%10;return!n||a&&!(c%a)&&d(n/10,c);
}

C89 doesn't have a boolean type. Hope that works.
Also I used a second parameter to pass a copy of the original number through the stack, but the definition can be anything. To get the correct result you just have to call the function with the same value for both parameters (d(128, 128)).
EDIT: Applied suggested edits by an anonymous user

Take a look at http://codegolf.stackexchange.com/review/suggested-edits/17160 , someone gave you some golfing suggestions

Specifically against the rules. One parameter.

Yup, this post is actually why I decided to make that rule, as it didn't seem right that the user should do the duplication instead of the program.

I guess I'll have to add a wrapper function. Does the declaration of that function add to the byte count?

C / C++, 58 bytes (44 in body)
Invokes Undefined Behaviour (see comments)
int d(int i){int j=i;while(i&&!(j%(i%10)))i/=10;return!i;}

true and false are 1 and 0, but feel free to add one character to the signature to return a bool.
And for fun, a recursive version which is smaller if you allow calls of the form r(128,128)
Edit: Now disallowed by the rules:

C / C++, 53 bytes (33 in body)
int r(int i,int j){return!i||!(j%(i%10))&&r(i/10,j);}

#1 dies with a floating point exception for numbers containing a 0 because j%(i%10) will be illegal for i%10 = 0.

A floating point exception? Weird. It works perfectly on my compiler but you're right, it's undefined behaviour. Not sure what the general PCG stance on compiler-dependent UB is.

What's "compiler-dependent UB"? Either it's UB or it isn't (and division by zero, or rather modulo zero, is indeed UB). UB shouldn't be allowed because literally anything could happen. We may assume your program will run on a machine that will blow up and kill everyone around it when a division by zero happens. Now, I'm sure you want us all to live... C does have a concept of implementation-defined behavior, but dividing by zero doesn't fall under that.

@etheranger: Division by 0 is called floating point exception for historical reason: http://stackoverflow.com/questions/16928942/why-does-integer-division-by-zero-result-in-a-floating-point-exception

@JeroenMostert: I'd say over 90 % of all C answers on this site invoke UB. As long as it works with some compiler on some machine, the answer is considered valid.

@etheranger: What compiler did you use?

@sudo: then I'd say the C golfers need more discipline. It's one thing to have a clever hack that only works on the Foobar Bletchley because only that has programmable degaussing coils, and another to do something that renders your entire program susceptible to irreversible mangling by an optimizing compiler. That said, I suppose this sorts itself out by voting and setting appropriate rules in the question (and if all else fails, ignoring pundits like me :-)).

@n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳  Neat, nice history lesson :D

@sudo Green Hills for ARM - kind of niche, I know.
@ JeroenMostert I meant the results were compiler/cpu dependent, not the defined-ness. And I would tend to agree with avoiding it - terrible practice for anywhere but PCG and I wouldn't have posted in the first place if I'd noticed. I'm leaving it as-is for now given how unimportant the content of the answer actually is.

CJam, 15 bytes
{_Abf{_g{%}*}:|!}

This is a block, the closest thing to a function in CJam. I'm only counting the body (i.e. omitting the braces). You can use it as follows:
128{_Abf{_g{%}*}:|!}~

Or if you want to test a series of inputs, you can do
[128 12 120 122 13 32 22 42 212 213 162 204]{{_Abf{_g{%}*}:|!}~}%

The block leaves 0 (falsy) or 1 (truthy) on the stack to indicate the result. (CJam doesn't have a Boolean type.)
Test it here.
Explanation:
_               "Duplicate input.";
 Ab             "Get base-10 digits.";
   f{      }    "This maps the block onto the list of digits, supplying the input each time.";
     _g         "Duplicate digit, get signum S (0 or 1).";
       { }*     "Repeat this block S times.";
        %       "Take input modulo digit.";
                "This leaves an array of zeroes for divisible digits, non-zeroes
                 for non-divisible digits, and non-zero junk for zeroes.";
            :|  "Fold OR onto this list. One could also sum the list with :+";
              ! "Logical NOT. Turns 0 into 1, and non-zero values into 0.";

Alternative, also 15 bytes
{:XAb{X\_X)?%},!}

Explanation
:X              "Store input in X.";
  Ab            "Get base-10 digits.";
    {       },  "Filter this list by the result of the block.";
     X\         "Push another copy of X, swap with digit.";
       _        "Duplicate digit.";
        X)      "Push X+1.";
          ?     "Select digit itself or X+1, depending on whether digit is 0 or not.";
           %    "Take modulo. X%(X+1) will always be nonzero for positive integers.";
              ! "Logical NOT. Turns an empty list into 1 and a non-empty list into 0.";

C11 - 44 Bytes in function body
Another C version, non recursive and without a floating point exception.
bool digit_multiple(int i)
{
    for(int n=i;i%10&&n%(i%10)<1;i/=10);return!i;
}

This will also work in C++, Java, and most other C-like languages.
Edited to include the improvement of primo's comment.

A version that compiles in Java (1.7.0_45-b18): int n=i;for(;i%10>0&&n%(i%10)<1;i/=10);return i<1;, one byte shorter than the OP's code.

PHP: 45 Characters
The character count is for the body of the function.
It is necessary to only pass the first parameter.
function t($n, $k=true, $s='str_split'){foreach($s($n)as$b)$k=$k&&$n%$b===0;return$k;}

"and only passes in one numeric parameter"

PHP: 85 bytes (64 bytes on the body)
For this function to work, simply pass a string or a number.
0 will correctly return false.
The code:
function f($n,$i=0){for($n.='';$n[$i]&&$t=!($n%$n[$i++]););return$t&&$i==strlen($n);}

Please, DO NOT SET THE 2ND PARAMETER!
Javascript: 76 bytes (61 bytes on the body)
This is a rewrite of the previous function.
Not much changed between both versions.
Here is the code:
function f(n){for(i=0,n+='';n[i]/1&&(t=!(n%n[i++])););return t&&i==n.length}

Polyglot: Javascript+PHP 187 217 bytes (76 84 bytes without boilerplate):
Why I made it?
Because of reason and maybe because I can!
Just ignore the error on PHP: it works anyway!
No longer needed, this was fixed by removing 3 bytes.
Here is the masterpiece:
if('\0'=="\0"){function strlen($s){return $s['length'];}}
function toString(){return'';}
function f($n){for($i=0,$n=$n.toString();$n[$i]/1&&($t=!($n%$n[$i++])););return $t&&$i==strlen($n);}

You can run this code both on your console and on a PHP interpreter!

Old version:
if('\0'=="\0"){function strlen($s){return $s['length'];}}
function s($s){return('\0'=="\0")?$s+'':str_replace('','',$s);}
function f($n,$i){for($i=0,$n=s($n);$n[$i]/1&&($t=!($n%$n[$i++])););return $t&&$i==strlen($n);}

"and only passes in one numeric parameter". Without this you can eval($x) and pass whole code in $x

@abc667 Sorry, but I don't get it.

Octave, 33 (39 including function setup)
Using numeric-to-matrix conversion:
f=@(a)sum(mod(a./(num2str(a)-48),1))==0

Divide number elementwise by matrix X, where X is made by converting number to string and subtracting 48 to go from ASCII values to numbers again. Take modulo 1 to get decimal part of each division, confirm that all of these are zero (if any are NaN because of /0, the sum will be NaN and hence not zero).
Sample input using www.octave-online.net:
f=@(a)sum(mod(a./(num2str(a)-48),1))==0
for j=[128,12,120,122,13,32,22,42,212,213,162,204]
f(j)
end

Output:
ans =  1
ans =  1
ans = 0
ans =  1
ans = 0
ans = 0
ans =  1
ans = 0
ans =  1
ans = 0
ans =  1
ans = 0

How can we test this?

http://octave-online.net/ - enter the code definition from above and then (for example) f(128). Will add output

I had found the compiler and tried it before asking. But it seems to work fine (except for f(123), which is divisible by 1, 2 and 3). But it does work for the test-cases provided.

PHP - 74 71 64 Characters
Golfed:
function t($n){while($n>1){if(!($b=$n%10)||($n%$b)){return 0;}$n/=10;}return 1;}

Less Golfed:
function t($n){
    while($n>1){
        if( !($b=$n%10) || ($n%$b) )
            { return 0; }
        $n/=10;
    }
    return 1;
}

Test Results:
(Code)
$ans = array(128,12,120,122,13,32,22,42,212,213,162,204);
foreach($ans as $a)
{ echo "$a -> ".(t($a)?"True":"False").PHP_EOL; }

(Output)
128 -> True
12 -> True
120 -> False
122 -> True
13 -> False
32 -> True
22 -> True
42 -> True
212 -> True
213 -> True
162 -> False
204 -> False

MATLAB - 39 characters
function [b] = dividesSelf(i)
b=all(~mod(i,sscanf(num2str(i),'%1d')))
end

BASH - 117 characters
f(){ [[ $1 =~ 0 ]]&& return 0 || r=;n=$1;for((i=0;i<${#n};i++));do r=$(($r+${n}%${n:$i:1}));done;return $(($r==0));}

tests
for N in 128 12 120 122 13 32 22 42 212 213 162 204; do
  f $N
  echo "${N} ->  $?"
done

128 ->  1
12 ->  1
120 ->  0
122 ->  1
13 ->  0
32 ->  0
22 ->  1
42 ->  0
212 ->  1
213 ->  0
162 ->  1
204 ->  0

Javascript ES6, 33
n=>(""+n).replace(/./g,x=>n%x)==0

Test:

f=n=>(""+n).replace(/./g,x=>n%x)==0
console.log(
           [128, 12,  120,  122, 13,   32,   22,   42,  212, 213,  162, 204]
.map(f) == "true,true,false,true,false,false,true,false,true,false,true,false"
)

@Optimizer I've updated language name, sorry for dissonance.

JavaScript, ES6 would be the best choice :)

@Optimizer Ok :)

The f= does not count towards the bytecount, since it's not a recursive function. This is actually 33 bytes.

@PatrickRoberts, thanks, updated.

GNU Awk: 53 characters
The counted part:
for(;++i<=split($1,a,//);)r=r||!a[i]||v%a[i];return!r

The entire function:
function self_divisible(v, i, r)
{
    for (; ++i <= split($1, a, //); )
        r = r || ! a[i] || v % a[i]

    return ! r
}

As Awk has no boolean values, returns 1 tor true and 0 for false.

JavaScript (ES6) 30
Function with one numeric parameter. Using % and subtraction, no need to special case '0' because 0%0 is NaN in JavaScript.
Edit Saved 1 char thx DocMax
F=n=>[for(d of t=n+'')t-=n%d]&&t==n

Just for fun, abusing the rule about not counting function signature, 4
Check=(n,t=n+'',q=[for(d of t)n-=t%d])=>t==n

Test In FireFox/FireBug console
console.log([128, 12, 120, 122, 13, 32, 22, 42, 212, 213, 162, 204]
.map(x=>+x + ' -> ' + F(x)).join('\n'))

Output
128 -> true
12 -> true
120 -> false
122 -> true
13 -> false
32 -> false
22 -> true
42 -> false
212 -> true
213 -> false
162 -> true
204 -> false

I'm going to say no to inputting a string.

The Firefox console is happy with the replacement of of(t=n+'') with just of t=n+'' to save 1.

05AB1E, 6 5 bytes
Ñ¨K0‹

Try it online!
Explanation
Ñ¨K0‹  full program with implicit input  [213]
Ñ      push divisors                     [1, 3, 71, 213]
 ¨     remove the last element           [1, 3, 71]
  K    push a without b                  [2]
   0   push 0                            [2] [0]
    ‹  push a < b                        [0]
       output implicitly

K uses the implicit input [213] as a and the current stack [1, 3, 71] as b.

You answer seems to fail for 297 (not divisible by 2).

Stacked, 11 bytes in the function body
[:10 tb\|all]

Try it online!
Takes a number from the stack and returns 1 if they are all divisible or 0 otherwise.
Explanation
[:10 tb\|all]
[           ]   anonymous function (the function body)
 :10 tb         push digits of the number (*t*o *b*ase 10)
       \|       vectorized "divides" test
         all    ensure all are truthy (i.e. not 0)

The method signature can be whatever you want. Just count the function body. I think this is 11 bytes.

@EriktheOutgolfer thanks, what an odd rule

J, 14 bytes
0=1#."."0@":|]

Try it online!
Small improvement on existing J answer.

Vyxal, 3 bytes
fḊg

Try it Online!
Explained
fḊg
f   # flatten input to get list of digits
 Ḋ  # divisible by
  g # minimum value of the individual lists whether the digit is divisible or not.
    #   If it is, `1`, if not `0`. So if 1 digit is not divisible, it returns `0` in the list, and the program takes it as the minimum.

Japt, 7 bytes
Handling 0s cost a couple of bytes (x/0 = Infinity).
ìeÈ©UvX

Try it
ìeÈ©UvX     :Implicit input of integer U
ì           :Convert to digit array
 e          :Does each return true
  È         :When passed through the following function as X
   ©        :  Logical AND with
    UvX     :  Is U divisible by X

Ruby, 32 bytes
->n{n.digits.all?{_1>0&&n%_1<1}}

Attempt This Online!

Fig, \$3\log_{256}(96)\approx\$ 2.469 bytes
a%f

Try it online!
I really gotta fix a.
a%f # Returns 0 for truthy, "true" for falsey
 %  # Modulo the number
  f # By each of its digits
a   # Any != 0?

Thunno 2, 3 bytes
dḊp

Attempt This Online!
Explanation
dḊp  # Implicit input   ->  128
d    # Cast to digits   ->  [1,2,8]
 Ḋ   # Divisible?       ->  [1,1,1]
  p  # Product          ->  1
     # Implicit output

Batch - 202 Bytes
Takes input from stdin - C:\div.bat 128.
@echo off&setLocal EnableDelayedExpansion&set s=%1&set c=%1&set l=0
:c
if defined s set/Al+=1&set "s=%s:~1%"&goto c
for /l %%a in (1,1,!l!)do set/aa=%c%%%%%a&if !a!==1 echo false&goto :EOF
echo true

Java - (64)
This is the shortest I can come up with:
boolean t(int a) {
    int x=a,t=0;do t+=x%10>0?a%(x%10):0;while((x/=10)>0);return t<1;
}

If you don't count the method overhead, just the body, it scores 64.

Scala, 38 characters
def isDivisibleByAllDigits(n: Int) = n.toString.forall(d=>d>48&&n%(d-48)<1)

ES6, not exactly a golf, just screwing around with the Y-combinator
let dividesSelf = v =>
  !(l =>
    (f => f(f))
    (f => l(n => f(f)(n))))
  (f => n => n + v % n)
  (v >> 1);

A little minified, 52 characters long
let dividesSelf = v =>
  !(l=>(f=>f(f))(f=>l(n=>f(f)(n))))(f=>n=>n+v%n)(v>>1)

The fact I beat about half of the answers is surprising.

Python 2, ~85 ~83 characters (~75 ~73 just the function body)
Staying all numeric; count includes newlines and spacing.
def t(n):
 r=n
 while r:
  r,i=divmod(r,10)
  if not i or n%i:return 0>1
 return 1>0

assert(t(128)==True)
assert(t(12)==True)
assert(t(120)==False)
assert(t(122)==True)
assert(t(13)==False)
assert(t(32)==False)
assert(t(22)==True)
assert(t(42)==False)
assert(t(212)==True)
assert(t(213)==False)
assert(t(162)==True)
assert(t(204)==False)

Alternative, 88 characters in the function body:
def t(n):return '0' not in `n` and not reduce(lambda a,b:a or b,[divmod(n,int(x))[1] for x in `n`])

The approach feels shorter with map/reduce but with Python code it isn't.

J (16)
+/@:|~_1&(10&#.)

Returns 0 when true, another number otherwise

Java 7, Score = 96 76
Since I can't compete with your number based method, I used a character based method instead. a has the input integer in it.
int c=0;for(char e:(""+a).toCharArray())c+=(e-=-48)<1||a%e>0?1:0;return c<1;

Here it is golfed indented with structure code:
public class T{

    public static void main(String[] args){
        System.out.println(new T().test(Integer.parseInt(args[0])));
    }

    boolean test(int a){
        int c=0;
        for(char e:(""+a).toCharArray())
            c+=(e-=-48)<1||a%e>0?1:0;
        return c<1;
    }

}

Here it is completely expanded:
public class Test{

    public static void main(String[] args){
        System.out.println(new Test().test(Integer.parseInt(args[0])));
    }

    boolean test(int number){
        String numberString = "" + number;
        int failed = 0;
        for (int a = 0; a < numberString.length(); a++){
            int charAt = numberString.charAt(a) - '0';
            if (charAt == 0 || number % charAt != 0){
                failed++;
            }
        }
        return failed < 1;
    }

}

Edit: Used Mathew Kirschbaum's suggestions to shorten code size.

On first glance, I see a few places where you can shorten this by relatively large amounts. First, you can change for(;d<b.length();d++) to for(char d:b). That form of for is essentially a foreach loop. That will also  shorten b.charAt(d) to just d, as well as remove the declaration of d in your second statement. Since b isn't used anywhere in the code other than the for condition anymore, you can get rid of it entirely and just replace the previously changed for(char d:b) to for(char d:a+""). That brings you to 62 or so.

According to http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.14.2, you cannot use a for each loop to iterate over a string. You can only iterate over collections and arrays. I'll try to find something that is similar, though.

PHP - 91 characters
function divides($n) {
    foreach(array_map('intval', str_split($n))as$i)if($i==0||$n%$i!=0)return false;return true;
}

foreach ([128, 12, 120, 122, 13, 32, 22, 42, 212, 213, 162, 204] as $n) {
    echo "\n" . $n . ' -> ' . divides($n);
}

This is code golf, so please shorten your code as much as you can (e.g. by removing unnecessary whitespace) and include byte count in your answer.

You could golf it to $x=1;foreach(str_split($n)as$i)$x&=$i&&$n%$i==0;return(bool)$x;

Mathematica, 53 bytes (46 byte body)
f[x_]:=AllTrue[IntegerDigits@x,#!=0&&Divisible[x,#]&]

f@x_ := Tr[x~Mod~IntegerDigits[x]] == 0

PHP, 59 Characters
Where $n is the number you're checking
foreach(str_split($n)as$v)if($n%$v!=0){echo 0;exit;}echo 1;

You can reduce this code further echo 0;exit; can simply be die('0');

One of the requirements is to return the boolean value if supported by the language and PHP certainly has true and false.

Haskell, 55
let f x =(\s->all(>'0')s||all((<1).(x`mod`).read.(:[]))s)$show x

Counting characters after the = sign as per the rules.

Python 2, 41 bytes
Size not including f=lambda j:.
f=lambda j:all(j%int(i)==0if i>"0"else 0for i in`j`)

Argument supplied must be an integer.
Basically what this does is iterates through the integer (after converting it to a string) and checks the divisibility.

i>"0" Lexicographical comparisons are your friend :)

@FryAmTheEggman Great, thanks!

You know.. sometimes I think I must be crazy. This is twice that I've seen the lexical golf, but not the numeric one... j%int(i)>0 ... :/

I mean j%int(i)<1 >_<

Java 104
Uses recursion. This test (i==0) is required to stop divide by zero error.
public boolean d(int n,int k)
{
int i=k%10;return (k<10)?(k>0)&&(n%k==0):(i==0)?false:(n%i==0)&d(n,k/10);
}

All ==0 can be shortened to <1. (i==0)?false: can be replaced by (i>0)&&.

(k<10)?(k>0)&&(n%k==0): can be replaced by (n>0)&(k<1)||. We will let the function recurse once more and check the base case there.

Go - 47 chars
func dividesSelf(i int) bool {
    for n:=i;i%10>0&&n%(i%10)<1;i/=10{};return i==0
}

Runnable on Go Playground: http://play.golang.org/p/67DQXWnwOT

Bash, 49
Exits with 0 if the number is divisible, other exit code (and a warning) if not.
f () { [ `<<<$1 sed "s/./+$1%\0/g"|cut -c2-|bc` -eq 0 ]; }

Clojure, 71 bytes
(fn[n](every? integer?(map #(if(=\0 %1)1.1(/ n(- 48(int %1))))(str n))))

JAGL Alpha 1.2 - 24 bytes
Obviously this wouldn't count in a real contest, because the language came out after the question, but I'm still gonna answer just for fun. Assumes that the number is the only value on the stack, and sets the top value of the stack to 1 or 0, depending on whether the number is divisible by its digits or not.
dg{i}/d0en{{SdcS%n}/A}Sf

Explanation:
dg                         Duplicate number and convert to string
  {i}/                     Convert that to an array of digits
      0en                  If 0 is in the array, push 0, else push 1
         {                 Block to be run if 0 not in array
          {SdcS            Swap, duplicate, cycle, swap
               %n}         Push 1 if divisible by digit, 0 otherwise
                  /A       Map over list and push 1 if all values are 1, otherwise 0
                    }Sf    Run block if 0 not in array

JavaScript, 89 81 70 bytes
function d(n){a=(n+"").split("");for(i in a)if(n%a[i]||1/0==n/a[i])return!1;return!0}

Sorry for that. 2. I don't see the problem here. Can you please explain? 3. Ok, I'll recalculate.

Why dud you roll back your edit?

Javascript, 82 81 80 bytes
a=prompt(q=1);b=a.split('');while(d=b.pop())q=q&!(a%d);alert(a.indexOf(0)+1?0:q)

R, 40 chars
f=function(n)all(n%%scan(t=gsub("(.)","\\1 ",n))%in%0)

%% is vectorized. scan(t=gsub("(.)","\\1 ",n) is a trick that I stole from an old answer by flodel, to split a number into its digits. %in%0 instead of simply negating the results allows for detection of NA (resulting from mod 0; NA==0 gives NA, !NA gives NA but NA%in%0 gives FALSE).
> f(120)
Read 3 items
[1] FALSE
> f(128)
Read 3 items
[1] TRUE
> f(12)
Read 2 items
[1] TRUE
> f(213)
Read 3 items
[1] FALSE
> f(212)
Read 3 items
[1] TRUE
> f(42)
Read 2 items
[1] FALSE

TI-BASIC, 29
Adapted from my answer to Generate Monday Numbers.
Input X
int(10fPart(X10^(-randIntNoRep(1,1+int(log(X
not(max(remainder(X,Ans+2Xnot(Ans

To disqualify numbers that contain zeroes, I replace all zeroes with 2X, which will not divide X.
I don't count the Input X in the code size, because it is analogous to a method signature.

Hassium, 130 Bytes
func i(n){m=n.toString();if(m.contains("0"))return false;foreach(d in m)if(n%d.toString().toDouble()!=0)return false;return true;}

Run and see expanded version here

K (oK), 13 bytes
Solution:
f:{~+/(48!$x)!'x}

13 bytes excludes function definition (+4) per specification.
Try it online!
Examples:
f 1024
0
f 128
1
f 333
1
f 334
0

Explanation:
Evaluation is performed right-to-left.
Convert (e.g.) 128 => 1 2 8. 128 mod each 1 2 8 => 0 0 0. Sum of this is 0. Not of this is 1:
f:{~+/(48!$x)!'x} / the solution including function definition
f:{             } / assign lambda function to f
               x  / implicit single parameter
             !'   / mod (!) each-left with each-right
      (     )     / do this together
          $x      / string x, 128 => "128"
       48!        / mod ascii values with 48, "128" => 1 2 8
    +/            / sum over results
   ~              / not, 0 => 1, anything else => 0

PHP, 44 bytes
function f($n,$s=str_split){
    foreach($s($n)as$d)$f|=!$d||$n%$d;return!$f;
}

Try it online.

Jelly, 3 bytes
ọDẠ

Try it online!
This is a link, i.e. a function in Jelly. Since Jelly doesn't have specific boolean values, this returns 1 for True and 0 for False.

Python 2: 36 38 Bytes
Excluding f=lambda n:
f=lambda n:all([not n%(int(a)or n-1)for a in`n`])

Similar to the other python solution.
Works because x or 0 returns x if x != 0.
Maybe some edge cases around 0-3 or something.
Edit: Didn't work, fixed it

all(n%(int(a)or~-n)<1for a in`n`) saves a few bytes.

J, 18 Bytes (21 with function definition)
d=:0:=+/@:(|~"."0@":)

Explanation:
d=:                     | Define d
                  ":    | Format into string
             "."0       | Turn into array of digits
           |~           | Starting Number mod each element
      +/                | Sum
   0:=                  | Test if it’s equal 0. Returns 1 for true, 0 for false

Other characters are for ensuring functions compose properly.

Python 2, 53 bytes
lambda s:all(s%int(i)==0 if i!='0'else 0 for i in`s`)

Try it online!

43 bytes

Mathematica - 93ish characters
Robert G Wilson v gives us the following for Mathematica:
Function definition:
fQ[n_] :=
  Block[{id = Union[IntegerDigits[n]]},
   Union[IntegerQ[#] & /@ (n/id)] == {True}];

To call:
Select[Range[487], fQ[#] &]

Output (ignoring divide by zero complaints):
{1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22, 24, 33, 36, 44, 48, 55,
66, 77, 88, 99, 111, 112, 115, 122, 124, 126, 128, 132, 135, 144,
155, 162, 168, 175, 184, 212, 216, 222, 224, 244, 248, 264, 288, 312,
315, 324, 333, 336, 366, 384, 396, 412, 424, 432, 444, 448}

How can you have -ish on a character count?

Converting to Community Wiki, as this is not your own work.

Oh, dear, the hallway monitor police are out. I gave full full credit, but I've broken some mysterious "rule" and so get castigated. This is precisely why I've given up even trying to contribute to StackExchange: aside from the privileged core who got in early, they just look down their noses at anyone new. Thanks for the -1.

Scala, 44 bytes
def f(n:Int)=n+""forall{k=>k>48&&n%(k-48)<1}

Try it online!

error: recursive method f needs result type

authors: n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳

authors: حافظ على مجرش

authors: م̷ص̷ط̷ُف̷َي̷ ٵ̷ ل̷ش̷ُت̷ۆ̷ر̷ي̷

authors: อนุชา เรืองสวัสดิ์

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Undo the square roots
Your job is to convert decimals back into the sum of the square roots of integers. The result has to have an accuracy of at least 6 significant decimal digits.
Input:
A number indicating the number of square roots and a decimal indicating the number to approximate.
Example input:
2 3.414213562373095

Output:
Integers separated by spaces that, when square rooted and added, are approximately the original decimal accurate to at least 6 significant decimal digits.
Zeros are not allowed in the solution.
If there are multiple solutions, you only have to print one.
Example output (in any order):
4 2

This works because Math.sqrt(4) + Math.sqrt(2) == 3.414213562373095.
This is code golf. Shortest code (with optional bonus) wins!
There is always going to be a solution but -10 if your program prints "No" when there is no solution with integers. In addition, -10 if your program prints all solutions (separated by newlines or semicolons or whatever) instead of just one.
Test cases:
3 7.923668178593959 --> 6 7 8
2 2.8284271247461903 --> 2 2
5 5.0 --> 1 1 1 1 1
5 13.0 --> 4 4 9 9 9 --> 81 1 1 1 1 --> 36 9 4 1 1 etc. [print any, but print all for the "all solutions bonus"]

And yes, your program has to finish in finite time using finite memory on any reasonable machine. It can't just work "in theory," you have to be able to actually test it.

If there are multiple solutions, does it matter which solution we print?.
E.g. for your last test case (5 13.0), this is also a valid solution: 81 1 1 1 1

And are zeros allowed in the solution?

Is the input always space-separated?

And is entering input via function call allowed?

Also, what about duplicate solutions? For the first example, is our code allowed to print all six permutations of 6 7 8 for the second bonus?

Sorry, another question: What can the first number be? Can it be 1 or 0?

@Sp3000 It can be 1 but not 0.

a) Finite time can be a long time. And finite memory might be more than I have available. b) I think you forgot to address some of the other comments.

@Sp3000 Yes input is always space separated.

@Jakube Yes as well.

@MartinBüttner Sorry, a) I suppose you can print permutations of the same solution if it shortens your code and b) the main point of that rule was that you have to at least test your code once. I didn't want to put a hard number but if your code takes a day you will probably run out of patience although technically it's a valid solution. Essentially, you can't post a solution that says "It takes 2 years to solve the test cases."

@soktinpk So, my Pyth answer can run the first 2 tests in less than 5 seconds, but it needs about 1 gig of ram to run 5,5.0 and about 1TB of ram to run 5,13.0 (which, while very large, are not impossible). I have tested an algorithmically identical solution where the only difference is memory usage. This solves 5,13.0 in about 12 hours on my machine. Is this ok?

Sorry, I can't get the meaning of the 'No' bonus. All solutions are with integers.

@FryAmTheEggman Yes, that's okay because it did terminate in 12 hours right?

Python 3, 90 - 10 = 80
def S(N,x,n=[],i=1):
 if x*x<1e-12>N==0:print(*n)
 while.1+x*x>i:S(N-1,x-i**.5,n+[i]);i+=1

(Mega thanks to @xnor for tips, especially the restructuring of the for loop into a while)
A simple recursive attempt. It starts off with the target number and continuously subtracts square roots until it hits 0 or lower. The function S can be called like S(2,3.414213562373095) (the second argument is assumed to be positive).
The program doesn't just print out all solutions, it prints out all permutations of solutions (a little extraneous, I know). Here's the output for the last case: Pastebin.
A slight tweak gives a 98 - 10 = 88 solution which doesn't print permutations, making it more efficient:
def S(N,x,n=[]):
 *_,i=[1]+n
 if x*x<1e-12>N==0:print(*n)
 while.1+x*x>i:S(N-1,x-i**.5,n+[i]);i+=1

And just for fun, this 99 - 10 = 89 one is about as efficient as it gets (unlike the others, it doesn't blow the stack on S(1,1000):
def S(N,x,n=[]):
 *_,i=[1]+n
 if x*x<1e-12>N:print(*n)
 while(.1+x*x>i)*N:S(N-1,x-i**.5,n+[i]);i+=1

Note that, although we have a mutable default argument, this never causes a problem if we rerun the function since n+[i] creates a new list.

Proof of correctness
In order to end up in an infinite loop, we must hit some point where x < 0 and 0.1 + x2 > 1. This is satisfied by x < -0.948....
But note that we start from positive x and x is always decreasing, so in order to hit x < -0.948... we must have had x' - i0.5 < -0.948... for some x' > -0.948... before x and positive integer i. For the while loop to run, we must also have had 0.1 + x'2 > i.
Rearranging we get x'2 + 1.897x' + 0.948 < i < 0.1 + x'2, the outer parts implying that x' < -0.447. But if -0.948 < x' < -0.447, then no positive integer i can fit the gap in the above inequality.
Hence we'll never end up in an infinite loop.

You can avoid abs with x*x<1e-12.

I think this while loop works to replace the for: while.1+x*x>i:S(x-i**.5,n+[i]);i+=1, having initialized i=1 in the function parameters. The idea is to avoid needing to convert to ints. The .1 is to handle float inaccuracies; I think it's safe against infinite loops.

@xnor I've implemented the first tip for now. I'm still checking the correctness of the second one, but if it's good then that's a lot of bytes saved! (Also I actually expected you to post a solution :P)

And with N now a function argument, it's shorter to recurse down with N-1 and check when N==0 rather than len(n)==N.

@Sp3000 I'm convinced now that the .1 is safe; I can chat you an argument if you'd like.

ECLiPSe Prolog   -  118 (138-20)
I used the following implementation of Prolog: http://eclipseclp.org/
:-lib(util).
t(0,S,[]):-!,S<0.00001,S> -0.00001.
t(N,S,[X|Y]):-A is integer(ceiling(S*S)),between(1,A,X),M is N-1,T is S-sqrt(X),t(M,T,Y).

This is a very naive, exponential approach.
Listing all possible solutions takes time to cover all combinations (edit: the range of visited integers now decreases at each step, which removes a lot of useless combinations).
Here follows a transcript of a test session. By default, the environment will try to find all possible solutions (-10) and prints "No" when it fails to do so (-10).
As Sp3000 properly noted in the comment, it also prints "Yes" when it succeeds. That surely means I can remove 10 more points ;-)
[eclipse 19]: t(1,0.5,R).

No (0.00s cpu)
[eclipse 20]: t(2,3.414213562373095,R).

R = [2, 4]
Yes (0.00s cpu, solution 1, maybe more) ? ;

R = [4, 2]
Yes (0.00s cpu, solution 2, maybe more) ? ;

No (0.01s cpu)
[eclipse 21]: t(3,7.923668178593959,R).

R = [6, 7, 8]
Yes (0.02s cpu, solution 1, maybe more) ? ;

R = [6, 8, 7]
Yes (0.02s cpu, solution 2, maybe more) ? ;

R = [7, 6, 8]
Yes (0.02s cpu, solution 3, maybe more) ?
[eclipse 22]: t(5,5.0,R).

R = [1, 1, 1, 1, 1]
Yes (0.00s cpu, solution 1, maybe more) ? ;
^C

interruption: type a, b, c, e, or h for help : ? abort
Aborting execution ...
Abort
[eclipse 23]: t(5,13.0,R).

R = [1, 1, 1, 1, 81]
Yes (0.00s cpu, solution 1, maybe more) ? ;

R = [1, 1, 1, 4, 64]
Yes (0.00s cpu, solution 2, maybe more) ? ;

R = [1, 1, 1, 9, 49]
Yes (0.00s cpu, solution 3, maybe more) ?
[eclipse 24]:

(Edit) Regarding performance, it is quite good, at least compared to other ones (see for example this comment from FryAmTheEggman). First, if you want to print all results, add the following predicate:
    p(N,S):-t(N,S,L),write(L),fail.
    p(_,_).

See http://pastebin.com/ugjfEHpw for the (5,13.0) case, which completes in 0.24 seconds and find 495 solutions (but maybe I am missing some solutions, I don't know).

It also prints "Yes" when it succeeds! Oh Prolog.

Erlang, 305-10 302-10
f(M,D)->E=round(D*D),t(p(E,M,1),{M,E,D}).
p(_,0,A)->A;p(E,N,A)->p(E,N-1,A*E).
t(-1,_)->"No";t(I,{N,E,D}=T)->L=q(I,N,E,[]),V=lists:sum([math:sqrt(M)||M<-L])-D,if V*V<0.1e-9->lists:flatten([integer_to_list(J)++" "||J<-L]);true->t(I-1,T)end.
q(I,1,_,A)->[I+1|A];q(I,N,E,A)->q(I div E,N-1,E,[I rem E+1|A]).

This function returns string "No" or a string with values separated by spaces. It (inefficiently) processes every possible values encoding them into a large integer, and starting with higher values. 0 are not allowed in the solution, and encoded 0 represents all ones. Error is squared.
Example:
f(1,0.5).               % returns "No"
f(2,3.414213562373095). % returns "4 2 "
f(3,7.923668178593959). % returns "8 7 6 "
f(5,5.0).               % returns "1 1 1 1 1 "
f(5,13.0).              % returns "81 1 1 1 1 "

Please be patient with f(5,13.0) as function search space is 13^10. It can be made faster with 2 additional bytes.

Python 3 2: 173 159 - 10 = 149
Explanation:
Each solution is of the form x_1 x_2 ... x_n with 1 <= x_1 <= x^2 where x is the target sum. Therefore we can encode each solution as an integer in base x^2. The while loop iterates over all (x^2)^n possibilities. Then I convert the integer back and test the sum. Pretty straight forward.
i=input;n=int(i());x=float(i());m=int(x*x);a=m**n
while a:
 s=[a/m**b%m+1for b in range(n)];a-=1
 if abs(x-sum(b**.5for b in s))<1e-5:print' '.join(map(str,s))

It finds all solutions, but the last test case takes way too long.

JavaScript (ES6) 162 (172 - 10) 173
Edit A little shorter, a little slower.
As a function with 2 parameters, output to javascript console. This prints all solutions with no repetitions (solutions tuples are generated already sorted).
I cared more about timing than about char count, so that it's easily tested in a browser console within the standard javascript time limit.
(Feb 2016 update) Current time for last test case: about 1 150 secs. Memory requirements: negligible.
F=(k,t,z=t- --k,r=[])=>{
  for(r[k]=z=z*z|0;r[k];)
  {
    for(;k;)r[--k]=z;
    for(w=t,j=0;r[j];)w-=Math.sqrt(r[j++]);
    w*w<1e-12&&console.log(r.join(' '));
    for(--r[k];r[k]<1;)z=--r[++k];
  }
}

ES 5 Version Any browser
function F(k,t)
{
  var z=t- --k,r=[];
  for(r[k]=z=z*z|0;r[k];)
  {
    for(;k;)r[--k]=z;
    for(w=t,j=0;r[j];)w-=Math.sqrt(r[j++]);
    w*w<1e-12&&console.log(r.join(' '));
    for(--r[k];r[k]<1;)z=--r[++k];
  }
}

Test Snippet it should run on any recent browser

F=(k,t)=>
{
   z=t- --k,r=[];
   for(r[k]=z=z*z|0;r[k];)
   {
      for(;k;)r[--k]=z;
      for(w=t,j=0;r[j];)w-=Math.sqrt(r[j++]);
      w*w<1e-12&&console.log(r.join(' '));
      for(--r[k];r[k]<1;)z=--r[++k];
   }
}

console.log=x=>O.textContent+=x+'\n'

t=~new Date
console.log('\n2, 3.414213562373095')
F(2, 3.414213562373095)
console.log('\n5, 5')
F(5, 5)
console.log('\n3, 7.923668178593959')
F(3, 7.923668178593959)
console.log('\n5, 13')
F(5, 13)

t-=~new Date
O.textContent = 'Total time (ms) '+t+ '\n'+O.textContent

(Edit) Below are the result on my PC when I posted this answer 15 months ago. I tried today and it is 100 times faster on the same PC, just with a 64 bit alpha version of Firefox (and Chrome lags well behind)! - current time with Firefox 40 Alpha 64 bit: ~2 sec, Chrome 48: ~29 sec
Output (on my PC - last number is runtime in milliseconds)
2 4
1 1 1 1 1
6 7 8
1 1 1 1 81
1 1 1 4 64
1 1 1 9 49
1 1 4 4 49
1 1 1 16 36
1 1 4 9 36
1 4 4 4 36
1 1 1 25 25
1 1 4 16 25
1 1 9 9 25
1 4 4 9 25
4 4 4 4 25
1 1 9 16 16
1 4 4 16 16
1 4 9 9 16
4 4 4 9 16
1 9 9 9 9
4 4 9 9 9
281889

Pyth 55 54 47-20 = 27
DgGHKf<^-Hsm^d.5T2^10_12^r1hh*HHGR?jbmjdkKK"No

Try it online.
Shamelessly borrows from xnor's comment ;)
This will run out of memory on any sane computer even for a value like 5,5.0. Defines a function, g, that can be called like g 3 7.923668178593959.
This python 3 program uses essentially the same algorithm (just doesn't do the "No" printing at the end, which could be done by assigning a variable to all the results, then writing print(K if K else "No")), but uses a generator, so it doesn't get a memory error (it will still take extremely long, but I've made it print as it finds the values):
This gave the exact same results that @Sp3000 got. Also, this took several days to finish (I didn't time it, but around 72 hours).
from itertools import*
def g(G,H):
    for x in product(range(1,int(H*H+2)),repeat=G):
        if (H-sum(map(lambda n:n**.5,x)))**2<1e-12:print(*x)

Mathematica - 76 - 20 = 56
f[n_,x_]:=Select[Union[Sort/@Range[x^2]~Tuples~{n}],Abs[Plus@@√#-x]<10^-12&]

Examples
f[2, 3.414213562373095]
> {{2, 4}}
f[3, 7.923668178593959]
> {{6, 7, 8}}
f[3, 12]
> {{1, 1, 100}, {1, 4, 81}, {1, 9, 64}, {1, 16, 49}, {1, 25, 36}, {4, 4, 64}, {4, 9, 49}, {4, 16, 36}, {4, 25, 25}, {9, 9, 36}, {9, 16, 25}, {16, 16, 16}}

How does this print No? Also, the output isn't space separated. Also, can't you use Tr@ instead of Plus@@? And you might be able to save some characters by changing Select to Cases, the function at the end to a pattern, and making f an unnamed pure function.

Haskell, 87 80 - 10 = 70
This is a recursive algorithm similar to the Python 3 program of @Sp3000. It consists of an infix function # that returns a list of all permutations of all solutions.
0#n=[[]|n^2<0.1^12]
m#n=[k:v|k<-[1..round$n^2],v<-(m-1)#(n-fromInteger k**0.5)]

With a score of 102 99 92 - 10 = 82 we can print each solution only once, sorted:
0#n=[[]|n^2<0.1^12]
m#n=[k:v|k<-[1..round$n^2],v<-(m-1)#(n-fromInteger k**0.5),m<2||[k]<=v]

Python 3 - 157 174 169 - 10 = 159
Edit1: Changed the output format to space-separated integers instead of comma-separated.
Thanks for the tip of removing the braces around (n,x).
Edit2: Thanks for the golfing tips! I can trim off another 9 chars if I just use an == test instead of testing for approximate equality to within 1e-6, but that would invalidate approximate solutions, if any such exist.
Uses itertools to generate all possible integer combinations, hopefully efficiently :)
I haven't found a way to add printing "No" efficiently, it always seems to take more than 10 extra characters.
from itertools import*
n,x=eval(input())
for c in combinations_with_replacement(range(1,int(x*x)),n):
 if abs(sum(z**.5for z in c)-x)<1e-6:print(' '.join(map(str,c)))

Your program has the wrong output format (commas instead of spaces). Also, you can shave off 2 bytes by removing the braces around n,x.

I seem to be getting SyntaxErrors when I try the eval line...

@Sp3000: try enter 3,7.923668178593959. You need the ','

4 little improvements: from itertools import* saves 1, removing the space z**.5for saves 1, and removing the [] in sum(z**.5for z in c) saves 2 and removing the () in if(...) saves 1.

Would a change to Python 2 and using n,x=input() be more compact?

Also, according to https://mothereff.in/byte-counter#from%20itertools%20import%2a%0An%2Cx%3Deval%28input%28%29%29%0Afor%20c%20in%20combinations%5fwith%5freplacement%28range%281%2Cint%28x%2ax%29%29%2Cn%29%3A%0A%20if%20abs%28sum%28z%2a%2a.5for%20z%20in%20c%29-x%29%3C1e-6%3Aprint%28%27%20%27.join%28map%28str%2Cc%29%29%29 this is 166 bytes.

Scala (397 bytes - 10)
import java.util.Scanner
object Z extends App{type S=Map[Int,Int]
def a(m:S,i:Int)=m updated(i,1+m.getOrElse(i,0))
def f(n:Int,x:Double):Set[S]={if(n==0){if(x.abs<1e-6)Set(Map())else Set()}
else((1 to(x*x+1).toInt)flatMap{(i:Int)=>f(n-1,x-Math.sqrt(i))map{(m:S)=>a(m,i)}}).toSet}
val s=new Scanner(System.in)
f(s.nextInt,s.nextDouble)foreach{(m:S)=>m foreach{case(k,v)=>print(s"$k "*v)};println}}

If there are no permutations, then this program prints nothing.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

authors: Геннадий Пупкин

sort: votes


text:
Balanced Ternary Converter
Credits for the challenge idea go to @AndrewPiliser. His original proposal in the sandbox was abandoned and since he has not been active here for several months, I have taken over the challenge.
Balanced ternary is a non-standard numeral system. It is like ternary in that the digits increase in value by a factor of 3 as you go further to the left - so 100 is 9 and 1001 is 28.
However, instead of having values of 0, 1 and 2, the digits have values of -1, 0, and 1. (You can still use this to express any integer.)
For this challenge, the digit meaning +1 will be written as +, -1 will be written as -, and 0 is just 0. Balanced ternary does not use the - symbol in front of numbers to negate them like other numeral systems do - see examples.
Your task is to write a complete program which takes a 32-bit decimal signed integer as input and converts it to balanced ternary. No built-in base conversion functions of any sort are allowed (Mathematica probably has one...). Input can be on standard input, command-line arguments, etc.
Leading zeroes may be present in input but not in output, unless the input is 0, in which case the output should also be 0.
Examples
These are conversions from balanced ternary to decimal; you will have to convert the other way.
+0- = 1*3^2 + 0*3^1 + -1*3^0 = 9 + 0 + -1 = 8
+-0+ = 1*3^3 + -1*3^2 + 0*3^1 + 1*3^0 = 27 + -9 + 0 + 1 = 19
-+++ = -1*3^3 + 1*3^2 + 1*3^1 + 1*3^0 = -27 + 9 + 3 + 1 = -14

Oh wait, I've just noticed there's a question on balanced dozenal - is this a duplicate?

As I mentioned in the sandbox, I think it's closer to the challenge about standard phinary representations. But it's probably not a duplicate of either.

Python 2: 58 chars
n=input()
s=""
while n:s="0+-"[n%3]+s;n=-~n/3
print s or 0

Generates the balanced ternary digit-by-digit from the end. The last digit is given by the residue n%3 being -1,0, or +1. We then remove the last digit and divide by 3 using Python's floor-divide n=(n+1)/3. Then, we proceed recursively with the new last digit until the number is 0.
A special case is needed for the input 0 to give 0 rather than the empty string.

The specs don't allow this, but if one could write a function instead of a program and output the empty string for 0, a 40 char solution would be possible.
g=lambda n:n and g(-~n/3)+"0+-"[n%3]or""

Better to use n*"."and in the function-only case. Also print s or 0 works better :P

@Nabb Good call on s or 0. I had tried n*"."and, but it fails when n<0.

@MartinBüttner Pyth's longer answer was just due to use of a non optimal algorithm.

@Optimizer Well, obviously, and that's why I've upvoted the Python answer that got the better algorithm first. :P

Pyth, 71 24 23
L?+y/hb3@"0+-"%b3bk|yQ0

This is a recursive solution, based on @xnor's 40 character recursive function. y constructs the baanced ternary of the input, by finding the last digit using the mod 3 index, and then uses the fact that the rest of the digits are equal to the balanced ternary for (n+1)/3, using floored division. Then, it calls the function, returning the result, or 0 if the input is 0.
Try it here.

Is there an online Pyth interpreter?

There is, I'll add it to the post.

Your link is broken. I reccomend Try it online!, which you will use from now on whenever you need an interpreter for anything. By the way, your code appears to not work, for me it just return the input.

@Pavel It worked two years ago, when I wrote it. The current online Pyth interpreter is https://pyth.herokuapp.com/ If you want to run the above code, you can check out the interpreter from back then from https://github.com/isaacg1/pyth , which has a complete version controlled history of the language.

CJam, 24 bytes
I came up with this independently and I think this is, most probably, the only way to handle this.
li{_3%"0+-"=\_g+3/}h;]W%

Algorithmically, its similar to xnor's answer.
Try it online here
How it works:
li{               }h                 "Read input, convert to integer and run the code block"
                                     "until stack has 0 on top";
   _3%                               "Copy and get modulus 3";
      "0+-"=                         "Take the correct character based on the above modulus";
            \_g+                     "Swap, copy and take signum of the number and add"
                                     "that to it, incrementing the number if positive,"
                                     "decrementing otherwise";
                3/                   "Integer divide by 3 and continue until 0";
                    ;]               "Pop the residual 0 and wrap everything in array";
                      W%             "Reverse to get in binary format (right handed)";

Is the "increment if positive, decrement if negative" bit necessary? why not just increment?

@isaacg Try it out ;)

Is the rounding on CJam's division different?

@isaacg - Rounding - no. CJam integer division does not round. It floors

But floor towards zero or -inf?

@isaacg towards 0

JavaScript (E6) 68
A complete program, as requested, with I/O via popup. The core is the R function, 49 bytes.
Not so different from the other recursive solutions, I guess.
Taking advantage of the automatic conversion between string and number to avoid a special case for "0"
 alert((R=(n,d=(n%3+3)%3)=>n?R((n-d)/3+(d>1))+'0+-'[d]:'')(prompt()))

Test in FireFox/FireBug console, using just the R function
['0','8','19','-14','414'].map(x =>x +': '+R(x))

Output
["0: 0", "8: +0-", "19: +-0+", "-14: -+++", "414: +--0+00"]

Am I missing something?  What's the point of d=(n%3+3)%3 when d=n%3 yields the same value for d?

@RLH not for negative values (not in JavaScript). -20%3 === -2%3 === -2. Instead -20 mod 3 should be 1, and (-20%3+3)%3 is 1 indeed

Mathematica, 54 characters
Similar to xnor's recursion
Unicode symbols are used to replace Floor,Part,!=
If[(t=⌊(#+1)/3⌋)≠0,#0@t,""]<>{"0","+","-"}〚#~Mod~3+1〛&

Output
Stored as f for brevity and written without unicode incase you can't view
f=If[(t=Floor[(#+1)/3])!=0,#0@t,""]<>{"0","+","-"}[[#~Mod~3+1]]&
f /@ {8, 19, -14, 414} // Column

+0-
+-0+
-+++
+--0+00

Mathematica - 157 154 146 128
The golfed version:
f=(s="";n=#;i=Ceiling@Log[3,Abs@#]~Max~0;While[i>=0,s=s<>Which[n>=(1+3^i)/2,n-=3^i;"+",n>-(1+3^i)/2,"0",1>0,n+=3^i;"-"];i--];s)&

And with indentation for legibility:
f = (s = ""; n = #; i = Ceiling@Log[3, Abs@#]~Max~0;
 While[i >= 0,
  s = s<>Which[
   n >= (1 + 3^i)/2, n -= 3^i; "+",
   n > -(1 + 3^i)/2, "0",
   1 > 0, n += 3^i; "-"
  ];
 i--];
s)&

Usage:
f[414]

Output:
+--0+00

Many thanks to Martin Büttner in reducing the number of characters.

GNU sed, 236 bytes
/^0/bV
:
s/\b9/;8/
s/\b8/;7/
s/\b7/;6/
s/\b6/;5/
s/\b5/;4/
s/\b4/;3/
s/\b3/;2/
s/\b2/;1/
s/\b1/;0/
s/\b0//
/[^;-]/s/;/&&&&&&&&&&/g
t
y/;/1/
:V
s/111/3/g
s/3\b/3:/
s/311/33!/
s/31/3+/
y/3/1/
tV
s/1/+/
y/1:/!0/
/-/{s/-//
y/+!/!+/
}
y/!/-/

Try it online!
Explanation
The first half of the code (less the first line) translates decimal to unary and comes straight from "Tips for golfing in sed." Then it translates unary to balanced ternary one trit at a time, which I'll demonstrate by working an example manually.
Before the final output, the ternary digits -, 0, and + are represented by !, :, and +, respectively.
For an interesting result, we start with -48, which has been converted to unary (with the - intact). To calculate the first (right-most) trit, we have to calculate the remainder of 48÷3. We can do this by replacing the 111s with 3s:
-111111111111111111111111111111111111111111111111 │ s/111/3/g
# => -3333333333333333

48÷3 has no remainder, so no 1s remain, and we know our first trit is : (for 0), so we replace it:
-3333333333333333 │ s/3\b/3:/
# => -3333333333333333:

Now we have our "ones place," so we know the remaining 3s represent the threes place. To keep the math working we have to divide them by 3, i.e. replace them with 1s:
-3333333333333333: │ y/3/1/
# => -1111111111111111:

Let's double-check our math: We have 16 (unary 1111111111111111) in the threes place and zero (:) in the ones place. That's 3✕16 + 1✕0 = 48. So far so good.
Now we start again. Replace 111s with 3s:
-1111111111111111: │ s/111/3/g
# => -333331:

This time our remainder is 1, so we put + in the threes place and replace the remaining 3s with 1s:
-333331: │ s/31/3+/; y/3/1/
# => -11111+:

Sanity check time: We have a 5 (unary 11111) in the nines place, 1 (+) in the threes place, and 0 (:) in the ones place: 9✕5 + 3✕1 + 1✕0 = 48. Great! Again we replace the 111s with 3s:
-11111+: │ s/111/3/g
# => -311+:

This time our remainder is 2 (11). That takes up two trits (+!), which means we have a carry. Just like in decimal arithmetic that means we take the rightmost digit and add the rest to the column to the left. In our system, that means we put ! in the nines place and add another three to its left, then replace all of the 3s with 1s to represent the 27s place:
-311+: │ s/311/33!/; y/3/1/
# => -11!+:

Now we don't have any 3s left, so we can replace any remaining unary digits with their corresponding trits. Two (11) is +!:
-11!+: │ s/11/+!/
# => -+!!+:

In the actual code this is done in two steps, s/1/+/ and y/1:/!0/, to save bytes. The second step also replaces :s with 0s, so it actually does this:
-11!+: │ s/1/+/; y/1:/+0/
# => -+!!+0

Now we check if we have a negative number. We do, so we have to get rid of the sign and then invert each trit:
-+!!+0 │ /-/ { s/-//; y/+!/!+/; }
# => !++!0

Finally, we replace !s with -s:
!++!0 │ y/!/-/
# => -++-0

That's it!

Clojure, 172 bytes
(let[s "0+-"](loop[x(Integer.(read-line))xs '()](if(= 0 x)(println(apply str xs))(let[y(mod x 3)x(int (Math/floor(/ x 3.0)))](recur(if(= y 2)(inc x)x)(cons(get s y)xs))))))
Readable version:
(let [s "0+-"]
  (loop [x  (Integer. (read-line))
         xs '()]
    (if (= 0 x)
      (apply str xs)
      (let [y (mod x 3)
            x (int (Math/floor (/ x 3.0)))]
        (recur (if (= y 2) (inc x) x) (cons (get s y) xs))))))

Welcome to Code Golf, and nice answer!

Stax, 17 bytes
ë1·âΓM¿├>Ö≥Er☺à┤3

Run and debug it
Shortest answer so far, but should be easily beaten by some golfing languages. The algorithm is the same as @xnor's Python answer.
ASCII equivalent:
z{"0+-";3%@+,^3/~;wr

JavaScript 108 102 (ES6, no recursive calls)
t=a=>{v="";if(0==a)v="0";else for(a=(N=0>a)?-a:a;a;)v="0+-"[r=(a%3+3)%3]+v,2==r&&++a,a=a/3|0;return v}

Original entry at 108
t=a=>{v="";if(0==a)v="0";else for(a=(N=0>a)?-a:a;a;)v=(N?"0-+":"0+-")[r=a%3]+v,2==r&&++a,a/=3,a|=0;return v}

Not as fancy as @edc65's answer... I'd appreciate any help reducing this further...

Clojure, 242 bytes
#(clojure.string/join""(map{1"+"0"0"-1"-"}(loop[x(vec(map read-string(clojure.string/split(Integer/toString % 3)#"")))](let[y(.indexOf x 2)](if(< y 0)x(let[z(assoc x y -1)](recur(if(= y 0)(vec(cons 1 z))(assoc z(dec y)(inc(x(dec y))))))))))))

Is this the longest Clojure answer so far?
Ungolfed (with comments):
(use '[clojure.string :only (split join)]);' (Stupid highlighter)
; Import functions

(defn ternary [n]
  (join ""
  ; Joins it all together
    (map {1 "+" 0 "0" -1 "-"}
    ; Converts 1 to +, 0 to 0, -1 to -
      (loop [x (vec (map read-string (split (Integer/toString n 3) #"")))]
      ; The above line converts a base 10 number into base 3,
      ; and splits the digits into a list (8 -> [2 2])
        (let [y (.indexOf x 2)]
        ; The first occurrence of 2 in the list, if there is no 2,
        ; the .indexOf function returns -1
          (if (< y 0) x
          ; Is there a 2? If not, then output the list to
          ; the map and join functions above.
            (let [z (assoc x y -1)]
            ; Converts where the 2 is to a -1 ([2 2] -> [-1 2])
              (recur
                (if (= y 0) (vec (cons 1 z))
                  ; If 2 is at the 0th place (e.g. [2 2]),
                  ; prepend a 1 (e.g. [-1 2] -> [1 -1 2])
                  (assoc z (dec y) (inc (x (dec y)))))))))))))
                  ; Else increment the previous index
                  ; (e.g. [1 -1 2] -> [1 0 -1])

8th, 179 171 167 characters
Here it is a complete program in 8th which takes a decimal signed integer as input and converts it to balanced ternary

: f "" swap repeat dup 3 n:mod ["0","+","-"] swap caseof rot swap s:+ swap dup n:sgn n:+ 3 n:/mod nip while drop s:rev ;
"? " con:print 16 null con:accept >n
f cr . cr

Test

? 414
+--0+00

The first time the program asks for a number to convert (as required). Then, it is possible to invoke the word f to convert more numbers as in the following line:

[ 8 , 19 , -14 , ] ( nip dup . space f . cr ) a:each drop

Output

8 +0-
19 +-0+
-14 -+++

Code explanation

"? " con:print 16 null con:accept >n

This is the code for input handling. The core of the code is inside the word f. Away from the golf course I would have used the word >bt instead of f. Here it is an ungolfed version of f (with comments):

: f \ n -- s
    ""   \ used for the first symbol concatenation
    swap \ put number on TOS to be used by loop
    repeat
        dup
        3 n:mod      \ return the remainder of the division by 3
        [ "0" , "+" , "-" , ]
        swap caseof  \ use remainder to take proper symbol
        rot          \ put previous symbol on TOS
        swap         \ this is required because "" should come first
        s:+          \ concatenate symbols
        swap         \ put number on TOS
        dup
        n:sgn n:+    \ add 1 if positive or add -1 if negative
        3 n:/mod nip \ put quotient only on TOS
    while drop
    s:rev            \ reverse the result on TOS
;

Brainfuck, 406 340 335 bytes
code (with added newlines for readability):
-[+>+[+<]>+]>-<,[->->+<<]+>[[-]<->]<[>>,<]>[<]>>>>++<<<[>-[<->-----]<+++>>>[>]>>++>++<<<<[[->>+>>+<<<<]<]>>>++>++<
[[-<<<<<+>>>>>]<<<<+++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]->[-]-->+[+[-<<+>>]>]>>]<<<<<<[[->>>+<<<]<]>,]
<<[>>>>>[[-<->]>]<<[++++<]<]>>>>>[>]+[<--[>->]>[-<+>]<]<<++>+<[>-]>[-<++>>]<<[>>--[<+>++++++]<<---[>++<++[>+++<-]]>.[-]<<]

Takes input as decimal string with an optional leading -
This is my first non-trivial Brainfuck program so there is certainly room for improvement.
Try it online
Commented version of code:
-[+>+[+<]>+]>-  constant 45
<,[->->+<<]+>[[-]<->]<[>>,<]>[<]> remember sign
>>>++<<< load 2 in cell 3
[ while input is not EOF
>-[<->-----]<+++ subtract 48 (ascii 0) from input
>>>[>]>>++>++<<<<[[->>+>>+<<<<]<]>>>++>++<  multiply by 10 (add number to shifted copy)
[  add next digit and handle carries
[-<<<<<+>>>>>]
<<<<+++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]
->[-]-->+[+[-<<+>>]>]>>
]
<<<<<<[[->>>+<<<]<]>
,] reset to start of loop
<<[>>>>>[[-<->]>]<<[++++<]<] flip number if negative
>>>>>[>]+[<--[>->]>[-<+>]<]<<++ strip leading zeros
>+<[>-]>[-<++>>]<< ensure zero is printed
[ print the number
  >>--[<+>++++++]< load 43 (char code of plus)
  <---[>++<++[>+++<-]]>.[-]<<
]

Java, 327 269 characters
My first try in code golfing. I don't know any of those really short languages, so here's a solution in Java. I'd appreciate advice to further shorten it.
import java.util.*;class a{public static void main(String[] h){int i=Integer.parseInt(new Scanner(System.in).nextLine());String r="";while(i!=0){if(i%3==2||i%3==-1){r="-"+r;}else if(i%3==1||i%3==-2){r="+"+r;}else{r="0"+r;}i=i<0?(i-1)/3:(i+1)/3;}System.out.println(r);}}

Try it here : http://ideone.com/fxlBBb
EDIT
Replaced BufferedReader by Scanner, allowing me to remove throws clause, but had to change import (+2 chars).
Replaced Integer by int. Unfortunately, program won't compile if there isn't String[] h in main.

You might be able to save a few bytes by using a Scanner instead of your BufferedReader. Also, String[] h and throws java.lang.Exception probably aren't necessary, and you might save a few more bytes by using int instead of Integer.

JavaScript (ES6), 51 bytes
v=>[...v].map(x=>t=3*t+((+x!=+x)?(x+1)-0:0),t=0)&&t

Loop through characters.  First multiply previous total times 3, then if isNaN(character) is true, convert the string (character + "1") to a number and add it, otherwise zero.

Shave off 3 bytes:  v=>[...v].map(x=>t=+(x!=0?x+1:0)+3*t,t=0)&&t

Shave off 1 more byte: v=>[...v].map(x=>t=+(x!=0&&x+1)+3*t,t=0)&&t

Stax, 14 bytes
ü♣ê⌠yù∞♪♦X=/ƒ├

Run and debug it

APL(NARS), 26 chars, 52 bytes
{+/(3*¯1+⍳≢⍵)×¯2+⌽'-0+'⍳⍵}

test:
  h←{+/(3*¯1+⍳≢⍵)×¯2+⌽'-0+'⍳⍵}
  h '+0-'
8
  h '+-0+'
19
  h '-+++'
¯14
  h ,'-'
¯1
  h ,'0'
0
  h ,'+'
1

possible it could be less if ⊥ is used but it is forbidden...

05AB1E, 20 bytes
ΔYÝ<ÀÅв3βÊ½¾}…0+-ÅвJ

Try it online!

Python 3, 66
Python 2 answer from xnor, ported to Python 3.
Note that official support for Python 2 ceases on January 1 2020.
n=eval(input())
s=""
while n:s="0+-"[n%3]+s;n=-~n//3
print(s or 0)

Raku (Perl 6) (rakudo), 52 53 bytes
{.&(my&g={$_??g(-+^$_ div 3)~ <0 + ->[$_%3]!!''})||0}

Attempt This Online!
Explanation
{.&(my&g={$_??g(-+^$_ div 3)~ <0 + ->[$_%3]!!''})||0}
    my&g={$_??g(-+^$_ div 3)~ <0 + ->[$_%3]!!''}      # g returns '' for 0
              g(-+^$_ div 3)                          # g(($_ + 1) div 3)
 .&(                                           )      # call g($_)
                                                ||0   # if this is falsy, then return 0

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Cyclically Equivalent Words
Cyclic Equivalence
Let L be a list of pairs of letters, for example [(a,b), (a,c)]. We call L a list of commutators. Two words are cyclically equivalent over L, if one can be transformed into the other using the following operations:

Cyclic shift: pop a letter from the beginning, and push it to the end.
Commutator swap: if the word begins with two letters that appear in L in either order, swap those letters.

For example, the words acabd and dcaba are cyclically equivalent over L, since we have the sequence of operations acabd -> caabd -> aabdc -> abdca -> badca -> adcab -> dcaba. However, the words acabd and acdab are not cyclically equivalent, since the letters b, c and d cannot be swapped with each other, so they can occur only in the order cbd, dcb or bdc in words that are cyclically equivalent to acbad.
The Challenge
You are given as input two words, and a list of commutators. You program should output a truth-y value (True, 1, etc.) if the words are cyclically equivalent over the list, and a false-y value (False, 0, etc.) otherwise. You don't have to output a sequence of operations in the positive case. The shortest answer (in bytes) is the winner.
Test Cases
[(a,b), (a,c)] acabd dcaba -> True
[(a,b), (a,c)] acabd acdab -> False
[(a,b), (a,d), (b,c), (b,d)] cdaddccabbdcddcababaaabbcbdccaccacdddacdbccbddaacccaddbdbbcadcccadadccbaaabdbcc ddcadbbcccdadbabcbcaadaccbbcdddaccdacddcababaaacbbdbccaccbacddadcdccaddabcbccda -> True
[(a,b), (a,d), (b,c), (b,d)] cdaddccabbdcddcababaaabbcbdcccacacdddacdbccbddaacccaddbdbbcadcccadadccbaaabdbcc ddcadbbcccdadbabcbcaadaccbbcdddaccdacddcababaaacbbdbccaccbacddadcdccaddabcbccda -> False

Clarifications

You can write either a function or a STDIN-to-STDOUT program.
The list of commutators can be given as a comma-separated string, a list of length-two strings, or a list of pairs of characters.
You can assume that the input words only contain alphanumeric ASCII symbols.
Your program should be able to process inputs of length 100 in a matter of seconds.
Standard loopholes are disallowed.

It's not obvious to me that this can be done in polynomial time. Is it known how to solve the word problem in groups whose presentations consist solely of commutation relations?

Never mind, I think I see how this can be done.

@xnor: Finding a fast enough algorithm is part of the challenge. ;) It is indeed not obvious, and I think there may be several essentially different solutions.

Python 413
Pretty efficient, although it does sacrifice a small amount of speed for length, such as calculating things every pass of a small for loop rather than precalculating it. I̶t̶ ̶s̶t̶i̶l̶l̶ ̶o̶u̶t̶p̶u̶t̶s̶ ̶a̶l̶l̶ ̶t̶h̶e̶ ̶t̶e̶s̶t̶ ̶c̶a̶s̶e̶s̶ ̶i̶n̶ ̶w̶e̶l̶l̶ ̶u̶n̶d̶e̶r̶ ̶a̶ ̶s̶e̶c̶o̶n̶d̶.̶
Edit:
I had to fix a bug which now makes it significantly less efficient for larger inputs.
X,Y,L=input();S=sorted;T=type
def E(s,c):
 l=[[]]
 for h in s:
    if h==c:l+=[h]
    elif all(h!=[b,a][j]for a,b in L for j,n in[(0,a),(1,b)]if n==c):
     if T(l[-1])==str:l+=[[]]
     l[-1]=S(l[-1]+[h])
 if T(l[0])==T(l[-1])!=str:return[l[0]+l[-1]]+l[1:-1]+[len(l[-1])]
 return l+[0]
print any(0==cmp(*[[E(s,c)for c in S(set(s))]for s in [X[j:]+X[:j],Y[i:]+Y[:i]]])for i in range(len(Y))for j in range(len(X)))

Test Cases
"acb", "abc", [('a','b')]
True (0 ms)

'acabd','dcaba',[('a','b'),('a','c')]
True (1 ms)

'acabd','acdab',[('a','b'),('a','c')]
False (2 ms)

'cdaddccabbdcddcababaaabbcbdccaccacdddacdbccbddaacccaddbdbbcadcccadadccbaaabdbcc','ddcadbbcccdadbabcbcaadaccbbcdddaccdacddcababaaacbbdbccaccbacddadcdccaddabcbccda',[('a','b'), ('a','d'), ('b','c'), ('b','d')]
True (62 ms)

'cdaddccabbdcddcababaaabbcbdcccacacdddacdbccbddaacccaddbdbbcadcccadadccbaaabdbcc','ddcadbbcccdadbabcbcaadaccbbcdddaccdacddcababaaacbbdbccaccbacddadcdccaddabcbccda',[('a','b'), ('a','d'), ('b','c'), ('b','d')]
False (6963 ms)

The basic algorithm does the following. For each letter, L, present, loop through the string constructing a list; anytime it encounters L it appends it to the list, any group of adjacent letters which can not be switched with L it appends to the list sorted, letters which can be switched with L are ignored.
For example when considering 'acabd' with the pairs [('a','b'),('a','c')], we would construct:
a : a, a, [d]
b : [c], b, [d] *
c : c, [b,d]
d : [a,a,b,c], d

which is equivalent to the result we get when we apply this to 'cabad' ('dcaba' shifted)
*Note here that the [c] and [d] should be considered one list
What is basically being done, is confirming for each letter that the order of it and the letters it can't switch with are the same. Since they cannot switch, they cannot 'pass' each other, so if the first string has two as followed by two ds followed by one a followed by one d than no matter how it's manipulated it can't be transformed into a string which has three as followed by three ds. Of course the order of the letters that it can't switch with is not an issue (they might be paired with each other and switchable), but their counts are, hence the sorting of the lists before comparison. In addition it's clear that any letters that can be switched don't matter at all for the purposed of comparison.
Using this algorithm the program could be made significantly more efficient; currently it loops through every possible transposition of both strings and compares them due to some issues with comparing cases in which there were lists bordering the beginning and end.

Is this program based on bubble sort?

@GerwinDox It doesn't really sort things, I'll update it with an explanation.

Haskell, 409
not fully golfed yet.
import Data.List
r((c,h):s)|l<-r s,(x,y)<-partition(\s->any(`elem`s)[c,h])l=nub(c:h:concat x):y
r _=[]
k s d|l<-sort$nub s=r[(x,y)|x<-l,y<-l,notElem(x,y)d,notElem(y,x)d,x/=y]
m a b c|elem c[a,b]=c|0<1=' '
e s d=[nub[map(m x y)s|x<-g,y<-g,notElem(x,y)d,notElem(y,x)d,x/=y]|g<-k s d]
q a b=and$zipWith(\a b->or[n a==n[drop i s++take i s|s<-b]|i<-[0..length$a!!0]])a b
f a b d=q(e a d)(e b d)
n=map$filter(/=' ')

this works on all the test cases.