text:
Check whether an integer is a power of 2 without using +,- operations
Write a program that checks if the integer is a power of 2.

Sample input:
8

Sample output:
Yes

Sample input:
10

Sample output:
No

Rules:

Don't use +,- operations.
Use some sort of input stream to get the number. Input is not supposed to be initially stored in a variable.
The shortest code (in bytes) wins.

You can use any truthy/falsy response (for instance, true/false). You may assume that input number is greater than 0.

Is it also allowed to output "true" instead of "yes" and "false" instead of "no"?

Yes, you can use any positive/negative response. Question is updated.

@gthacoder You may want to clarify input requirements, I'm almost feeling like I'm cheating using a variable with the value to check as input. Is that ok, seeing that GolfScript passes the value on the stack?

The pred function, when applied to an integer n, returns n - 1.  Are functions such as this, which are thin disguises around the forbidden operator, also forbidden?

@Wayne just like golfscript's ), or most c-based languages' --.

Can we output 1 or 0? 'T' or 'F'?

@JoachimIsaksson Good point. Input is supposed to be typed by user. Question is updated.

Requiring the input from a stream automatically penalizes languages such as AS3 or Java which don't have that sort of capability within arm's reach. Allowing "input" variables would level the playing field.

What is the range of valid input? This is important because a number of answers here break if the input is 0.

Don't worry about 0. Input number is supposed to be greater than 0. Question is updated.

@gthacoder Is -- alowed for C(++)? And unary - (negate)? What about negative constants? (-1)

@nightcracker Question is created with idea that you can't use the fact that if n & (n - 1) is equal to 0, then n is a power of 2 (reason why +, - are forbidden). Otherwise, you can use any operators.

@gthacoder But see my answer, I don't use + or - and it still works. I do use -1 though.

I am not seeing the need for plus or minus so much. It seems pretty easy to do it without.

Can you use return value instead of explicitly printing?

It is supposed to be a complete program with input and output.

If we use + in a regex, is that OK?

@O-I + OPERATION is forbidden, so + symbol in a regular expression is OK. I found you rewrote your answer without + anyway.

@gthacoder My C answer is smaller than vershov's.

@nightcracker Yes, you are right. My bad. Sorry. Question is updated.

@gthacoder Add some bonus for code that works also for 0 (return False). Many answers do not work for this case (should crash if use log, or return wrong answer).

Can you add Perl 6? It's a separate language to Perl 5, even with confusing name.

@xfix Good point. They differ fundamentally indeed. Question is updated.

if -1 as a constant is allowed I can get the javascript down to 28 characters (cannot post, need reputation!)
alert(((a=prompt())&a*-1)>1)

alert(!((a=prompt())&(a/3))) is also 28 characters and avoids the - sign altogether

Simple answer:log2 then check if it has numbers under the fp

Can input be unary?

Is there an upper limit to the range of valid inputs?

I know we're 3 years in the future now, but "+/- operators" is non-observable, or at the very least weakly defined.

GolfScript, 6 chars, no decrements
~.3/&!

Here's a solution that doesn't use the x & (x-1) method in any form.  It uses x & (x/3) instead. ;-) Outputs 0 if false, 1 if true.
Explanation:

~ evals the input string to turn it into a number,
. duplicates it (for the subsequent &),
3/ divides it by three (truncating down),
& computes the bitwise AND of the divided value with the original, which will be zero if and only if the input is zero or a power of two (i.e. has at most one bit set), and
! logically negates this, mapping zero to one and all other values to zero.

Notes:

Per the clarified rules, zero is not a valid input, so this code is OK, even though it outputs 1 if the input is zero.
If the GolfScript decrement operator ( is allowed, then the 5-character solution ~.(&! posted by aditsu is enough.  However, it seems to go against the spirit of the rules, if not the letter.
I came up with the x & (x/3) trick years ago on the Fun With Perl mailing list.  (I'm sure I'm not the first to discover it, but I did (re)invent it independently.)  Here's a link to the original post, including a proof that it actually works.

I think it is a bit silly really, golfscript allows one to write the exact solution that the OP wanted to exclude without actually breaking the rules.

@Tim: OK, here's one without decrements, then. ;)

how can this work? For example 7/3 = 2 (0010), so 7 & 2 = 0111 & 0010 = 0010 which clearly the last bit is not 1

@LưuVĩnhPhúc: No, but the second bit is.  Try doing long division by 3 in binary and it's pretty obvious why this always happens if the dividend has more than one bit set.

ah I misread this with "divisible by 2"

I am impressed. It is even shorter now.

My Pyth !%lQ1 beats this :) as long as it was invented after the question was posted, which I'm not sure about.

APL (7)
Yes, that's 7 bytes. Assume for the moment that I'm using IBM codepage 907 instead of Unicode and then each character is a byte :)
0=1|2⍟⎕

i.e. 0 = mod(log(input(),2),1)

Just wondering, what happens if you give it 0 or a negative number?

@aditsu I don´t know what infinity mod 1 is, but it certainly shouldn't be zero.

@TimSeguine Mathematica gives me Indeterminate when I try that.

GolfScript, 11 (for 1 (true) and 0 (false))
.,{2\?}%?0>

Put the number on the stack and then run.
GolfScript, 22 (for Yes/No)
.,{2\?}%?0>'Yes''No'if

I love how converting 1/0 to Yes/No takes as much code as the challenge itself :D
Warning: EXTREMELY inefficient ;) It does work fine for numbers up to 10000, but once you get that high you start to notice slight lag.
Explanation:

.,: turns n into n 0..n (. duplicate, , 0..n range)
{2\?}: to the power of 2
%: map "power of 2" over "0..n" so it becomes n [1 2 4 8 16 ...]
?0>: checks to see if the array contains the number (0 is greater than index)

1 byte shorter for Yes/No: .,{2\?}%?0<'YesNo'3/=; also I think you're cheating by asking to "Put the number on the stack", you should start with a ~.

Fails on 1, which is 2^0

Mathematica 28
Numerator[Input[]~Log~2]==1

For integer powers of 2, the numerator of the base 2 log will be 1 (meaning that the log is a unit fraction).
Here we modify the function slightly to display the presumed input.
We use # in place of Input[] and add & to define a pure function.
It returns the same answer that would be returned if the user input the number in the above function.
    Numerator[#~Log~2] == 1 &[1024]
    Numerator[#~Log~2] == 1 &[17]

True
False

Testing several numbers at a time.
    Numerator[#~Log~2] == 1 &&/@{64,8,7,0}

{True, True, False, False}

Perl 6 (17 characters)
say get.log(2)%%1

This program gets a line from STDIN get function, calculates logarithm with base 2 on it (log(2)), and checks if the result divides by 1 (%%1, where %% is divides by operator). Not as short as GolfScript solution, but I find this acceptable (GolfScript wins everything anyway), but way faster (even considering that Perl 6 is slow right now).
~ $ perl6 -e 'say get.log(2)%%1'
256
True
~ $ perl6 -e 'say get.log(2)%%1'
255
False

The reason that + and - are forbidden for this challenge, is because if x & (x - 1) is equal to 0, then x is a power of 2.

@ProgramFOX: I see. Interesting trick.

@ProgramFOX But x&~(~0*x) still works. That's only 2 characters longer.

Octave (15 23)
EDIT: Updated due to user input requirement;
~mod(log2(input('')),1)

Lets the user input a value and outputs 1 for true, 0 for false.
Tested in Octave, should work in Matlab also.

Works in Matlab also :)

R, 13 11
Based on the Perl solution. Returns FALSE or TRUE.
!log2(i)%%1

The parameter i represents the input variable.
An alternative version with user input:
!log2(scan())%%1

GolfScript, 5
Outputs 1 for true, 0 for false. Based on user3142747's idea:
~.(&!

Note: ( is decrement, hopefully it doesn't count as - :)
If it does (and the OP's comments suggest that it might), then please refer to Ilmari Karonen's solution instead.
For Y/N output, append 'NY'1/= at the end (7 more bytes).

Python, 31
print 3>bin(input()).rfind('1')

31 if you do bin(input()).rfind('1')<3

@Blender Well-spotted.  I'd used 2== because I figured it should work for nonpositive numbers too.   That's explicitly not required by the rules, so...

+1.  I was going to post print bin(input()).count('1')<2 at a total of 31 characters, but it's too similar to yours.

C, 48
main(x){scanf("%i",&x);puts(x&~(x*~0)?"F":"T");}

Can be shorter if unary negate is allowed, is longer if negative constants aren't allowed. Assumes two's complement.

* has higher precedence than binary &, you don't need the parens. And if return value is accepted (just asked) exit(x&x*-1) would be much shorter.

There is a -: x*-1.

@klingt.net yes, but that's part of a numerical constant. Technically, as it is worded now, only the operator - is forbidden.

Either way, I think you can get away with ~0 instead of -1 if necessary.

@Kevin But ~ has a higher presedence than *, so the parens are necessary.

Oh yes, missed that ~

That was also my initial idea, but i thougt that every -/+ sign was forbidden. I should read the specification the next time more carefully ;)

@klingt.net Replaced it with a version that uses no signs.

I decided to to use another approach, based on the population count or sideways sum of the number (the number of 1-bits).  The idea is that all powers of two have exactly one 1 bit, and no other number does.  I added a JavaScript version because I found it amusing, though it certainly won't win any golfing competition.
J, 14 15 chars (outputs 0 or 1)
1=##~#:".1!:1]1

JavaScript, 76 chars (outputs true or false)
alert((~~prompt()).toString(2).split("").map(Number).filter(Boolean).length)

This uses addition, which is precluded by the challenge.

Huh.  I've no idea what I was thinking when I wrote this... I've fixed it now so it actually follows the rules.

An equivalent JS solution is n=>n.toString(2).split(1).length==2 for 35 bytes

Clip, 9 8 7
!%lnxWO

Reads a number from stdin.
Explanation:
To start with, Z = 0, W = 2 and O = 1. This allows placing of W and O next to each other, whereas using 2 and 1 would be interpreted as the number 21 without a separating space (an unwanted extra character).
In Clip, the modulo function (%) works on non-integers, so, to work out if some value v is an integer, you check if v mod 1 = 0. Using Clip syntax, this is written as =0%v1. However, as booleans are stored as 1 (or anything else) and 0, checking if something is equal to 0 is just 'not'ing it. For this, Clip has the ! operator. In my code, v is lnx2. x is an input from stdin, n converts a string to a number and lab is log base b of a. The program therefore translates (more readably) to 0 = ((log base 2 of parseInt(readLine)) mod 1).
Examples:
8

outputs
1

and
10

outputs
0

Edit 1: replaced 0, 1 and 2 with Z, O and W.
Edit 2: replaced =Z with !.
Also:
Pyth, 5
Compresses the Clip version even further, as Pyth has Q for already evaluated input and a log2(a) function instead of just general log(a, b).
!%lQ1

Javascript (37)
a=prompt();while(a>1)a/=2;alert(a==1)

Simple script that just divides by 2 repeatedly and checks the remainder.

same idea with a for loop (also 37 chars) for(i=prompt();i>1;i/=2){}alert(i==1)

Mathematica (21)
IntegerQ@Log2@Input[]

Without input it is a bit shorter
IntegerQ@Log2[8]

True

IntegerQ@Log2[7]

False

⌊#⌋==#&@Log2@Input[]

@alephalpha That ends up using 24 bytes for the UTF-8 characters. Another 21-byte program is Log2@Input[]~Mod~1==0.

Ruby — 17 characters (fourth try)
p /.1/!~'%b'%gets

My current best is a fusion of @steenslag's answer with my own. Below are my previous attempts.
Ruby — 19 characters (third try)
p /10*1/!~'%b'%gets

Ruby — 22 characters (second try)
p !('%b'%gets)[/10*1/]

Ruby — 24 characters (first try)
p !!('%b'%gets=~/^10*$/)

there's still a "+" in your program

I know. :-/ I've asked for clarification whether '+' and '-' are strictly forbidden, or whether they can be used in other contexts besides addition and subtraction. I'm in the process of rewriting regardless.

Great improvement. It seems like it's the best Ruby result so far. I updated the leaders table in the question text.

@gthacoder Just combined steenslag's regex with my binary formatting. Definitely can't take all the credit.

JavaScript, 41 40 characters
l=Math.log;alert(l(prompt())/l(2)%1==0);

How this works: you take the logarithm at base 2 using l(prompt()) / l(2), and if that result modulo 1 is equal to zero, then it is a power of 2.
For example: after taking the logarithm of 8 on base 2, you get 3. 3 modulo 1 is equal to 0, so this returns true.
After taking the logarithm of 7 on base 2, you get 2.807354922057604. 2.807354922057604 modulo 1 is equal to 0.807354922057604, so this returns false.

You don't need to cast the input to a number; Math.log will do that already: "Each of the following Math object functions applies the ToNumber abstract operator to each of its arguments..."

Doesn't it suffer from numerical inaccuracies?

@MarkJeronimus: I actually don't know. It could be, but I haven't yet encountered an incorrect result.

JavaScript, 35
Works for bytes.
alert((+prompt()).toString(2)%9==1)

46 character version,
Works for 16 bit numbers.
x=(+prompt()).toString(2)%99;alert(x==1|x==10)

The trick works in most dynamic languages.
Explanation: Convert the number to base 2, interpret that string as base 10, do modulo 9 to get the digit sum, which must be 1.

What about 0x2ff, which in base 2 is 1111111111?

@PeterTaylor You're right, fixed

so the real thing your doing is checking for modulo 10 without a remainder, but you used 9 to shave a character of your code, +1!

This is kinda cheating but another method: alert(!(Number.MAX_VALUE%prompt()))

K/Kona (24 17)
d:{(+/(2_vs x))~1

Returns 1 if true and 0 if false. Any power of 2 has a single bit equal to 1:
2_vs'_(2^'(!10))
(,1
1 0
1 0 0
1 0 0 0
1 0 0 0 0
1 0 0 0 0 0
1 0 0 0 0 0 0
1 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0)

(this prints out all the powers of 2 (from 0 to 9) in binary)
So I sum up all the components of the binary expression of x and see if it's equal to 1; if yes then x=2^n, otherwise nope.

...knew I could make it smaller

@gthacoder: I made the code smaller, hope you can update you main post to reflect this!

Doesn't this use addition? And doesn't the question, err, forbid that?

python 3,   38
print(1==bin(int(input())).count('1'))

python,     32
However, the code doesn't work in every version.
print 1==bin(input()).count('1')

Notice that the solution works also for 0 (print False).

Upvoted because this was my solution as well.

What if you replace == with &?

@SimonT This is not true. Replacing the '==' with '&' will print 1 for every number that has odd number of '1' in its binary representation. Check for example 7=111. There are 3=11 ones. It will return 11&1 = 1.

Perl 5.10+, 13 + 1 = 14 chars
say!($_&$_/3)

Uses the same method from an old FWP thread as my GolfScript entry.
Prints 1 if the input is a power of two, and an empty line otherwise.
Needs to be run with perl -nE; the n costs one extra char, for a total of 14 chars.  Alternatively, here's an 18-character version that doesn't need the n:
say!(($_=<>)&$_/3)

C# (54 characters)
 Math.Log(int.Parse(Console.ReadLine()),2)%1==0?"Y":"N"

The task clearly states that input is not stored in a variable, it should be obtained from an input stream of some kind (like stdin), also, this is [tag:code-golf], try shortening your code a little, at least by removing whitespace

I think you just mean Int32, not ToInt32...

Ya ya. Thanks for pointing out Chris. Earlier it was Convert.ToInt32 and I wanted to change it to Int32.Parse to shorten it. :D

use int instead of Int32 for 2 fewer characters.

Rebmu (9 chars)
z?MOl2A 1

Test
>> rebmu/args [z?MOl2A 1] 7
== false

>> rebmu/args [z?MOl2A 1] 8
== true

>> rebmu/args [z?MOl2A 1] 9
== false

Rebmu is a constricted dialect of Rebol. The code is essentially:
z? mo l2 a 1  ; zero? mod log-2 input 1

Alternative
14 chars—Rebmu does not have a 'mushed' bitwise AND~
z?AND~aTIddA 3

In Rebol:
zero? a & to-integer a / 3

OCaml - 42 or 45
Since no-one has submitted an OCaml solution, I submit one inspired by nightcrackers C solution.
There is some debate as to whether the operator - includes unary negation. Other entries have managed to sidestep the issue by finding a solution that is equally short without unary negation. I instead give two answers:
let x=read_int()in 0=x land lnot(x* -1);;
and
let x=read_int()in 0=x land lnot(x*lnot 0);;
the ;; ends a group of statements in the OCaml interpreter and causes the result to be printed as - : bool = false or - : bool = true, which are clear negative/positive answers as required by the question.

GTB, 46 bytes
2→P`N[@N=Pg;1P^2→P@P>1E90g;2]l;2~"NO"&l;1"YES"

Python 2.7 (30 29 39 37)
EDIT: Updated due to user input requirement;
a=input()
while a>1:a/=2.
print a==1

Brute force, try to divide until =1 (success) or <1 (fail)

not a%2 can be written as a%2==0. Granted, this would be longer in many languages, but not Python.

@xfix Thanks, tested and updated.

or even better, a%2<1.

you have a space after 2. Removing that would save a byte!

APL (12 for 0/1, 27 for yes/no)
≠/A=2*0,ιA←⍞

or, if we must output text:
3↑(3x≠/A=2*0,ιA←⍞)↓'YESNO '

Read in A. Form a vector 0..A, then a vector 20..2A (yes, that's way more than necessary), then a vector comparing A with each of those (resulting in a vector of 0's and at most one 1), then xor that (there's no xor operator in APL, but ≠ applied to booleans will act as one.) We now have 0 or 1.
To get YES or NO: multiply the 0 or 1 by 3, drop this number of characters from 'YESNO ', then take the first 3 characters of this.

Ruby, 33, 28, 25
p /.1/!~gets.to_i.to_s(2)

Python, 35
print bin(input()).strip('0')=='b1'

Doesn't use not only +/- operations, but any math operations aside from converting to binary form.
Other stuff (interesting, but not for competition):
I have also a regexp version (61):
import re;print re.match(r'^0b10+$',bin(input())) is not None

(Love the idea, but import and match function make it too long)
And nice, but boring bitwise operations version (31):
x=input();print x and not x&~-x

(yes, it's shorter, but it uses ~-x for decrement which comtains - operation)

boothby's answers uses the same idea as my first, but is shorter :(

C, 65 bytes
main(k){scanf("%i",&k);while(k&&!(k%2))k/=2;puts(k==1?"T":"F");}

You can cut off 5 chars by using main(k){..., relying on the implicit int typing. It might be UB, but this is code golf. NEVER use something like that in production, of course.

Haskell (52 50)
k n=elem n$map(2^)[1..n]
main=interact$show.k.read

Python (33)
print int(bin(input())[3:]or 0)<1

int(bin(input()*2)[3:])<1 also works from the python shell with only 25 chars.

Python 2 - 23
x=input();print x&x/3<1

This is a direct port of the golf-script solution above, that beats the current best python solution by 8 characters. The order of operations works out amazingly well here.

Bash + dc + grep, 24
dc -e2o?p|grep -c ^10\*$

Reads from stdin.  Outputs "1" if a power of 2 and "0" otherwise:

$ dc -e2o?p|grep -c ^10\*$
8
1
$ dc -e2o?p|grep -c ^10\*$
10
0
$

Pure Bash (only builtins), 40
[[ `read a;printf %o $a` =~ ^[124]0*$ ]]

Reads from stdin.  Returns success (0) if a power of 2 and failure (1) otherwise:

$ [[ `read a;printf %o $a` =~ ^[124]0*$ ]]
8
$ echo $?
0
$ [[ `read a;printf %o $a` =~ ^[124]0*$ ]]
10
$ echo $?
1
$

Java 7, 124
This is pretty short in Java. Most of the program is just boilerplate code and to read the integer.
class H{public static void main(String[]b){int a=new java.util.Scanner(System.in).nextInt();System.out.println((a&a/3)<1);}}

I know it's been two years, but you can golf it by 2 bytes by simply using print instead of println.

SmileBASIC, 29 bytes
This is a fairly uncreative and basic (no pun intended) answer. 0 is false, 1 is true.
INPUT N
A=LOG(N,2)?(0OR A)==A

We know that if n is a power of 2, then log2(n) will be an integer. So, this calculates the base-2 log of N, our input number, and checks if it is an integer using the following method.
In SB there are actually two number types, doubles and integers. It also has automatic coercion between doubles and ints depending on the context. When a float is coerced to an int, it simply truncates the fraction and produces an integer which represents the whole part (assuming that number is in the valid integer size–signed 32 bit.) The bitwise OR operator OR expects both of its terms to be integers, so it will automatically cast doubles to ints. Thus, 0 OR double simply produces that double's whole part, which we then check against the original value. If these two are equal, it is a power of two.

A<<0 is shorter and doesn't need parentheses. And you can maybe use > or < instead of ==

Haskell, 47 bytes
(or 21 bytes if input/output can be function argument/return)
f 0=0
f 1=1
f n=f$n/2
main=interact$show.f.read

Returns 1 for powers of 2, and 0 otherwise.

Welcome to PPCG! Check out our Haskell golfing rules. In particular, just functions are fine, you don't need the last line. (Edit: Actually, this challenge is really old (2014) before functions were default. Maybe stick with the program.)

@xnor Thanks. I'm aware that this site usually accepts functions as answers, but I was unsure of the rules on function vs full program because the question states "Use some sort of input stream to get the number" and the other haskell answer does the same.  Also, I didn't realize that this question was so old. Is it considered rude to neco old questions here?

Python 2, 29,25 bytes
x=input();print x&x*~0==x

Try it online!
using x&x*~~x/~x is a modified version of x&(~x+1)! Since the later uses + had to use ~x which is equivalent to -x-1!

saved 4 bytes by using x*~0 instead of x*~~x/~x!

PHP, 86 chars
function P($a,$c){if($c==$a)return 1;if($c>$a)return 0;return P($a,$c*2);}echo P(x,2);

Replace x with the number you want to test.

I'm almost sure this can be shorter, by use of ternary operator... then again, ternary operator in PHP is rather strange, so you may need some parenthesis to enforce precedence.

PHP (58)
<?php $a=fgets(STDIN);while($a%2==0)$a/=2;echo $a==1?1:0;

Simple divide-by-2 loop and remainder check.

This shaves off few characters <?php $a=$argv[1];while(!($a%2))$a/=2;echo $a==1?1:0; Basically $argv[1] instead of fgets(STDIN)and!($a%2)instead ofa%2==0`

ActionScript 3 (63 characters*)
var r = Math.log(prompt())/Math.log(2);
return ( (r > 0) && (int(r) == r) );

* I'm going to ignore the fact that AS3 doesn't have a built-in prompt() method, (and hope AS3's lack of implementation doesn't get counted against me).
Extra white-space left in for readability and clarity, but not counted, since they can be removed before execution.

I'm also going to assume that the user didn't enter something funny like NaN.

In my opinion, using functions that don't exist is cheating. Just change this into JavaScript code, and replace int(r) with ~~r.

@xfix No! I refuse to support the use of an un-typed and classless language! Bah, humbug!

It's not that you use types or classes here. Also, you have definitely too many parens (return doesn't need parenthesis, and && has bigger precedence than both parenthesis groups).

@xfix Fine, you win, but may the records show that I still conscientiously object to the use of JavaScript as a serious programming languages.

GTB, 17
With 1/0
`Ar?A>1:A/2→A~A=1

With YES/NO (31)
`Ar?A>1:A/2→A@A=1$~"YES"#~"NO"&

JavaScript (43 characters when compacted, 35 for some browsers)
Readable version:
var r = Math.log(prompt()) / Math.LN2;
alert( (r > 0) && (~~r == r) );

Compacted version (credit goes to FireFly for helping me shave off even more characters):
r=Math.log(prompt())/Math.LN2;alert(~~r==r)

JS Fiddle: http://jsfiddle.net/IQAndreas/LFYg7/2/
EDIT: On the off chance that you use FireFox 25+ or any other browser with Math.log2(), only 35 characters are required (thanks to xfix for this suggestion):
r=Math.log2(prompt());alert(~~r==r)

You can remove the final semicolon and var. Also, JavaScript has Math.log2() function.

@xfix Nice, I also used several of your suggestions from the other answer. Thanks!

I save two characters by removing the >0, in which case the function will return 0 or false, but my soul is tormented enough by the shortcuts taken in this code anyway.

@xfix Regarding your edit, there is no Math.log2() function yet (or at least it's not standard across all browsers), it's still in the draft stage: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log2#Browser_compatibility

Oh, yeah, my mistake. I just prefer to use EcmaScript 6 for my code golf in JavaScript. But yeah, that makes sense - sometimes I mistake ES5 and ES6 stuff.

You can divide by Math.LN2 instead of Math.log(2). You can also get rid of the repeated Math via with:  with(Math)r=log(prompt())/LN2;alert(r>0&&~~r==r) (untested, but should work). (Edit: oh, duh, with(Math) doesn't win any additional characters..)

@FireFly Thanks, LN2 saved me three more characters.

Oh, I think you can drop x>0&& too, since the task specifies "check whether an integer", and Math.log takes negative integers to NaN, 0 to -Infinity and positive integers to positive values, and both NaN and -Infinity give you false for r == ~~r.

@FireFly Dropping that will let through a passed in value of 1, but should that count as a power of 2?

I'd say yes, as 2⁰ = 1.

Scheme 40
(display(=(mod(/(log(read))(log 2))1)0))

It displays #t for true and #f for false (the booleans in Scheme).
For true compatibility you need to add (import(rnrs)) or (import(scheme)) (for r7rs) but it works without that in ikarus and in most REPLs.

Perl 53
perl -pe '$_=unpack"b*",pack"L",$_;s!0!!g;s!111*!no!;s!1!yes!'

I can shave off 1 character if i use + in the re, not used for adding.

Use the y/// operator for shorter code: say unpack('b*',pack'l',$_)=~y/1//==1

Golfscript (17 14)
Works from input, using the base builtin for binary conversion and counting ones;
~2base{1=},,1=

Old version, 17 chars, without builtin conversions and without using the decrement operator as a substitute for -;
~2*:a 1{2*.a<}do=

~ lifts the input to an integer on the stack
2* multiplies by 2 to solve 2^0 problem
:a sets the variable a to the number to search for and leaves it on stack
1{2*.a<}do sets start value 1 and doubles as long as number<a
= compares the number to search for with the number generated

J - 17 15 bytes - not . ceiling (0==) . mod 1 . log2 . to_i . read keyboard
Result is 1 for True and 0 for False
0=1|2^.".1!:1,1

Yes/No version
(0=1|2^.".1!:1,1){'No',:'Yes'

Something weird seems to have happened to the title of your answer. You might want to fix it.

D (83 chars with boilerplate, 17 chars to get the solution)
import std.stdio;
void main(){
    int i;
    readf("%d", &i);
    while(!(i%2))i/2;
    writeln(i==1);
}

while the number is even divide by 2, when the result is 2 then it was a power of 2

Um, It says no - operation. I see one.

@Tim not anymore you don't :P

Perl 69
$_=<>;chomp;$s=1;while($s<$_){$s*=2;$r="Yes" if $s==$_}print $r||"No"

58: $_=<>;chomp;++$s;($s*=2)==$_&&($r=Yes)while$s<$_;say$r||No

I suppose ++ might count as addition. This is the same length: $_=<>;chomp;$s=1;($s*=2)==$_&&($r=Yes)while$s<$_;say$r||No

Perl 5 (36 or 29 bytes)
say sprintf('%b',<>)=~/^10*$/?Yes:No

If we don't want to strictly output "Yes" or "No", then we can go shorter:
say sprintf('%b',<>)=~/^10*$/

This second version outputs "1" for true, and "" for false.

C99 94 92 71
int main(){int a,i=1;scanf("%d",&a);while(i){if(a==i)return 1;i<<=1;}}

readable
#include <stdio.h>

int main() {
    int a, i=1;
    scanf("%d",&a);
    while(i){
        if(a==i) return 1;
        i<<=1;
    }
}

What it does
It XORs the input value with a power of 2, until the bit of variable i is shifted out and the value becomes 0. Only if the input value is also a power of 2 (with other words, only one bit in the input was set) the XOR resolves to zero.
The input will be compared with a power of 2 value, that is left shifted in every iteration (in other words multiplied by 2) and returns if both are equal, thus the input is also a power of 2.
On success 1 is returned, 0 otherwise.
Why C99?
Because the return value of a C program is implicitly defined as 0, if not specified, since C99. Compile with: gcc -std=c99 ...

!(a^i) instead of (a^i)==0

Actually, I believe you can just do if(a==i)

autohotkey -45bytes in txt file and 48 bytes with editor and lang.
MsgBox % mod(log(k)/log(2), 1) ? "no" : "yes"

Can't you remove the whitespace? this is [tag:code-golf] after all...

code golf? it is not. it is autohotkey. thanks for commenting in btw.

I mean the question is tagged with [tag:code-golf], which means that the entries need to be as short as possible

You should add a count of the bytes, and use \n=\n to make the language and count be bold.

if i remove spaces the code will break.

PHP, 55
<? if(fmod(log($argv[1],2),1)==0) echo 1; else echo 0;

Eg:
# php pow2.php 8
1
# php pow2.php 9
0

PHP w/ interactive I/O, 107
<? $h=fopen('php://stdin','r');$n=trim(fgets($h));fclose($h);if(fmod(log($n,2),1)==0) echo 1; else echo 0;

the OP didn't ask you to output "yes" or "no" so you can shave your code down to:
<? echo fmod(log($argv[1],2),1)==0
@serakfalcon shaved. Thanks for the suggestion.

Python (40 char)
p=lambda n:n>0and(n<2or n%2<1and p(n/2))

Works for negative number also (returning False)
C (39 chars)
p(n){return n>0&&(n<2||n%2<1&&p(n/2));}

or with trick, (work on old compilers without optimizing, withoput return operator returns last evaluated expression value) (32 chars)
p(n){n>0&&(n<2||n%2<1&&p(n/2));}

BASH, 48
x=`echo "obase=2;$1"|bc|rev|bc`;echo "$x==1"|bc

Takes input as a command line argument and returns 1 for true and 0 for false. You can easily modify it to echo Yes/No, but the bash if-construct makes it much longer.

39 characters: x=`bc<<<"obase=2;$1"|rev|bc`;bc<<<$x==1

No need for x at all - 37 bytes: echo \bc<<<"obase=2;$1"|rev|bc`==1|bc`

~-~! - 37
'=|*;~~==%['&*/~~]*|:'&^==~[@|1|]@|0|

I had to improvise with the number input...it's the Unicode value of the character you enter. Teehee.
This uses a recursive /2 solution.

JavaScript (EcmaScript 6) - 13 Characters
f=x=>!(x&x/3)

Creates a function f that takes a value and returns true (or false) if it is a power of 2 (or not) and will output the answer to the console.
Based on Ilmari Karonen's answer (so I included a few others of my own, below).
EcmaScript 6 can be run on FireFox or SpiderMonkey - no other browser/JavaScript engine yet supports EcmaScript 6 arrow functions. If you want to prompt for input then you can call it as an anonymous function (23 characters):
(x=>!(x&x/3))(prompt())

But it's less characters skip the function bit and just do:
JavaScript - 19 Characters
!((a=prompt())&a/3)

Will do the same as above but should run in all browsers and will prompt for input and output to the console (or in SpiderMonkey, you can replace prompt() [which doesn't exist as SpiderMonkey is command-line based] with readline()).
JavaScript (EcmaScript 6) - 20 Characters
f=x=>x>1?f(x/2):x==1

Creates a function f and, when called, will output the answer to the console.
JavaScript - 29 Characters
for(a=prompt();a>1;)a/=2;a==1

Same as above but will prompt the user for input and output to the console.
JavaScript - 32 Characters
for(a=prompt();!(a%2);)a/=2;a==1

JavaScript - 34 Characters
for(a=prompt();a==(a|0);)a/=2;a==1

Java 143
Thinking binary ( a power of 2 has always only one bit set so the compare with the integer with ionly highest bit set can only return true on powers of 2 (including the ominous 0 :P)
Update: shaved 2 bytes off due to a derp
enum P{public static void main(String[]a){int i=new java.util.Scanner(System.in).nextInt();System.out.print(i==(Integer.highestOneBit(i)*1));}}

Ungolfed
enum P;
{
    public static void main(String[]a)
    {
        int i = new java.util.Scanner(System.in).nextInt();
        System.out.print(i==(Integer.highestOneBit(i)*1));
    }
}

dc, 13 bytes
?[2~0=m]dsmxp

Reads input from STDIN.  Input is not explicitly stored in a variable, though it is stored on the stack - not sure if this too much rule-bending.
Successively divides by 2 until a 1 remainder is found.  Since dc doesn't have any native concept of truthy/falsey, I'm taking the liberty of defining my own here.  0 means true, any +ve integer means false:
$ for i in 1 2 3 15 16 17 65535 65536; do dc pow2.dc <<< $i; done
0
0
1
7
0
8
32767
0
$

Batch - 24 bytes
Stealing Ilmari's winning GolfScript answer...
@cmd/c"set/a!(%1/3^&%1)"

See explanation here.

Note: This question is older than Pyth, so this answer is not eligible to win.
Pyth, 5 bytes
!%lQ1

This is essentially identical to @marinus's APL answer. We take the log base 2 of the input, take it mod 1, and take the logical not.

Pyth, 6 bytes
!stjQ2

This answer converts the input to base 2, removes the first digit, sums the remainder, and takes the logical not.

Python (23)
int(bin(input())[3:])<1

You need a print statement in there...

AutoHotkey 33 bytes
a=%1%
While a>1
a:=a/2
Send % a=1

Input parameters are assigned to variables 1, then 2, etc. It means you have to assign it to another variable before using it in math because AHK will think you mean the number 1 and not the variable 1. It would be slightly shorter still but AHK treats a/=2 as a a floor divide by 2 instead of just a divide by 2 if and only if it is the left-most assignment operation on a line. I'm sure it has its reasons.

This is, surprisingly, slightly shorter than the method that uses log():
a=%1%
Send % Mod(Log(a)/Log(2),2)=0

Excel 19 bytes
=MOD(LOG(A1,2),2)=0

Nothing magical or tricky. Input is from cell A1. Returns TRUE or FALSE.

Haskell, 41 bytes
f n=mod(2^n)n<1
main=interact$show.f.read

Alternative:
main=interact$show.(<1).(mod=<<(2^)).read

Try it online!

43 bytes
main=interact$show.(1==).until(<2)(/2).read

Try it online. Halves x until it's less than 2, and checks if the result is 1.

Python 3.6, 30 bytes
from enum import _power_of_two

... there's a builtin lurking in the stdlib ...

Python:
print 0==int(bin(input())[3:] or 1)

10 is a false positive

Easiest way: An unsigned number is a power of 2 if only 1 BIT is set: if (!(n&(n-1))). Subtracting 1 inverts all BITs. if n=10000000b (80h/128), n&01111111b=0
if (!(n&(n-1)))
  printf("%d is a power of 2", n);
else
 printf("%d is NOT a power of 2", n);

// to get specific power of 2, search from
// right to left for 1st 0 BIT

int pow2(unsigned n) { // is power of 2?
  if (n&(n-1) || n<2) // if not, return 0
  return 0;
  n--;
  for (int i=1; n&1<<i; i++);
  return i; // 2^i
}

using + or - is not allowed...

did you even read the spec? you are using both + and -

Basic BASH command
# assume integer is stored in variable QUERY
[ "$[(${QUERY}/2)*2]" = "$QUERY" ] && echo "Is even" || echo "Is odd"

Takes advantage of how the shell does integer division, and drops any remainder.
weylin

"Power of 2" is not the same thing as "even".

Nuts - you're right. Sorry for any confusion.

#include <stdio.h>

int main(){
    int i=16;
    if(i&(i-1))
        printf("No\n");
    else
        printf("Yes\n");
    return 0;
}

You use - operation.

First of all, you use the - operator, that's not allowed. Also, the question is a code-golf, so the intension is that you code should be as small as possible, so remove whitespace if possible, and include the language and the character count in your answer.

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


text:
Make a move on a Go board
You are given a board position for a Go game and a move to play. You need to output whether the move is legal or not, and the new board position if it is legal.
A brief explanation of Go moves: the game consists of alternatively placing black and white pieces ("stones") in empty places on a square board. Sets of pieces of the same color that are connected to each other (4-way) are called groups. Empty places on the board that are adjacent to a group (also 4-way) are considered to be that group's "liberties". A group with 0 liberties is captured (removed from the board). A move that would cause its own group to be captured ("suicide") is illegal, unless it is capturing one or more opponent's groups (gaining liberties in the process so it is not actually captured).
For those concerned, you don't need to deal with ko (and superko), i.e. you can assume a ko capture is legal. If you don't know what that means, just follow the rules above and it will be fine.
Input: a number n between 2 and 19 (inclusive) representing the board size, followed by n lines of n numbers between 0 and 2 (inclusive) representing the board position, followed by 3 numbers separated by space, representing the move to make. In the board position, 0 means empty place, 1 means black stone and 2 means white stone. The move gives the column, the row and the color (1 or 2) of the stone to place. The column and row are 0-based, ranging from 0 to n-1 (inclusive) and counted in the same order as the board input.
You can assume that the given board position is legal (all groups have at least one liberty).
Output: a line containing 1 or 0 (or true/false if you prefer) if the move is legal or not, followed (only in case of a legal move) by the new board position in the same format as the input.
Score: Number of bytes of the complete source code, smaller is better. 20% additional penalty for use of non-ascii characters, and 20% additional penalty if your code can't be tested in Linux using freely available software.
Rules: No network connections and no 3rd party libraries. Your program should use the standard input and output streams, or the standard equivalent for your programming language.
Examples:
1) Input:

2
10
01
1 0 2

Output:

0

2) Input:

2
10
11
1 0 2

Output:

1
02
00

3) Input:

5
22122
22021
11211
02120
00120
2 1 1

Output:

1
00100
00101
11011
02120
00120

4) Input:

6
000000
011221
121121
122221
011110
000000
4 0 1

Output:

1
000010
011221
121121
122221
011110
000000

Python 3 (557 504 488)
import sys
s=sys.stdin
M=int(next(s))+1
j=Z=M*M-M
S=s.read(Z)
P=0
b=[0]*3
while j>0:j-=1+(j%M<1);b[int(S[j])]|=1<<j;P|=1<<j
N=lambda x:(x<<1|x>>1|x<<M|x>>M)&P&~x
def h(a,b):t=a|N(a)&b;return h(t,b)if t!=a else a
c,r,m=map(int,next(s).split())
o=m%2+1
p=1<<M*r+c
b[m]|=p
for n in(p<<1,p>>1,p<<M,p>>M):
 e=h(n&P,b[o])
 if~b[m]&N(e)<1<=n&b[o]:b[o]&=~e
_,B,W=b
g=~b[o]&N(h(p,b[m]))>=1>~_&p
print(+g)
q=''
while j<Z:
 r=1<<j
 if g*j%M>M-2:print(q);q=''
 else:q+='012E'[(r&B>0)+(r&W>0)*2]
 j+=1

Uses 3 bitfields to represent the board - one each for black, white, and empty spaces. Makes the find neighbors N and get chain h operations very concise.
An ungolfed version with lots of comments:
https://gist.github.com/airfrog/8429006

You have a LOT of spaces at the end of each line, the file as you posted it has 2732 bytes.

@aditsu That should be fixed now

Size is still wrong, should be 555 now :) Also I wonder if you can still save a few bytes by using more semicolons.

Bug? Input:
6 000000 011221 121121 122221 011110 000000 4 0 1
Output: 0. Added now as example 4.

That bug is fixed, I also found and fixed another bug while golfing it that you may want to add as an example. Input: 5 22100 20211 12211 12120 01120 1 1 2 Output should be 0.

Very nice implementation; please check my comments on your gist.

I'm still new to code golfing and was trying to unpack your code - @airfrog would it be possible to upload your 'ungolfed version with lots of comments' again? (The link doesn't work for me) Thanks a lot

On another note, I think o=m%2+1 can be changed to o=3-m

Python (9121004)
def o():
 n=int(raw_input(''))
 i=[raw_input('') for r in range(n+1)]
 b=[map(int,list(r)) for r in i[:n]]
 u,v,w=map(int,i[n].split(' '))
 if b[v][u]!=0:return 0
 b[v][u]=w
 if w==1:q=2
 elif w==2:q=1
 else:return 0
 f=[[],[],[]]
 h=[[],[],[]]
 g=[range(z*n,(z+1)*n) for z in range(n)]
 d=[(1,0),(-1,0),(0,1),(0,-1)]
 m=lambda z:max(0,min(n-1,z))
 t=[0,1,2,0,1]
 for j,s in enumerate(t):
  for r in range(n):
   for c in range(n):
    for y,x in map(lambda p:(m(r+p[0]),m(c+p[1])),d):
     if s==0:
      if b[y][x]==b[r][c]:
       if g[y][x]!=min(g[y][x],g[r][c]):
        t.insert(j+1,0)
       g[y][x]=g[r][c]=min(g[y][x],g[r][c])
     elif s==1:
      if g[r][c] not in h[b[r][c]]:
       h[b[r][c]].append(g[r][c])
      if b[y][x]==0 and g[r][c] not in f[b[r][c]]:
       f[b[r][c]].append(g[r][c])
    if s==2:
     if b[r][c]==q and g[r][c] not in f[b[r][c]]:
      b[r][c]=0
 h[w].sort()
 f[w].sort()
 if h[w]!=f[w]:return 0
 return "1\n"+'\n'.join([''.join(map(str,r)) for r in b])
print o()

Walk through: parse input, check if move is on an empty spot, make move, init "group" grid, simplify/minimize group grid by checking color of adjacant stones (s=0) and keep repeating until it is fully minimized, check for group liberties (s=1), remove opponent stones for groups with no liberties (s=2), repeat s=0 and s=1, check that all player groups have liberties, return result.
This can probably be shortened significantly...
Interactive Example runs:
2
10
01
1 0 2
0

2
10
11
1 0 2
1
02
00

5
22122
22021
11211
02120
00120
2 1 1
1
00100
00101
11011
02120
00120

6
000000
011221
121121
122221
011110
000000
4 0 1
1
000010
011221
121121
122221
011110
000000

Your program doesn't do anything, it only defines a function.

Run it interactively and call it with print o() as shown in the example run...

Nope. It is supposed to be a standalone program that you run from the command line. Besides, that would also make it shorter.

Fixed it by adding print o() on the last line

Why not just use the function body (outdented)? And I think you also fail the newly added example 4.

Fixed that, groups were not fully propagated. Code has become uglier and longer. I use a function so I can use return

Python 3.8: 480 479 424 359/366 344/351 bytes
Inspired by airfrog's accepted answer. Try it online!
o=open(0)
r=o.read
m=int(o.readline())+1
C=[*r(m*m-m)]+[' ']*m
y,x,c=map(int,r().split())
N=lambda p:[p+1,p-1,p+m,p-m]
p=x*m+y
C[p]=c
s=lambda P,c:[S(P,'0'),any((C[R]=='0')|(t[R]==str(c)and[S(R,'0'),s(R,c)][1])for R in N(P))][1]
for P in N(p):
 if C[P]==str(3-c):t=C[:];S=t.__setitem__;s(P,3-c)or(C:=t[:])
print(n:=s(p,c))
if n:print(*C,sep='')

(change last line to if n:print(*C[-m-1],sep='') if trailing spaces not allowed)
Older/slightly-different ungolfed version with comments:
from copy import deepcopy
n = int(input())

in_ = lambda x,y: x>=0 and x<n and y>=0 and y<n
neighbors = lambda x,y: [(x+dx, y+dy) for dx, dy in ((0,1),(0,-1),(1,0),(-1,0)) if in_(x+dx,y+dy)]

chars = [[*map(int, input())] for i in range(n)]
y,x,c = map(int, input().split())
chars[x][y] = c

def search(xx,yy,c):
    global chars
    tmp = deepcopy(chars)
    cue = [(xx, yy)]
    tmp[xx][yy] = 0
    nolib = True  # no liberty?
    while cue:
        xx,yy = cue.pop()
        for xxx,yyy in neighbors(xx,yy):
            if tmp[xxx][yyy]==c:
                cue.append((xxx,yyy))
                tmp[xxx][yyy] = 0
            elif chars[xxx][yyy]==0:
                nolib = False

    if nolib: chars = deepcopy(tmp)
    return nolib

for xx,yy in neighbors(x,y):
    if chars[xx][yy]==3-c: search(xx,yy,3-c)

if search(x,y,c):
    print(0)
else:
    print(1)
    for row in chars: print(*row, sep='')

source: Stack Exchange

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

sort: votes


text:
Write a mathematical function whose result is "hello world"
Write a mathematical function that results in an integer representation of "hello world"
For example "hello world" in hex is 68656c6c6f20776f726c64 so the goal will be to write a mathematical program that results in a number representing "hello world".
Here is a example of a possible solution using python:
print(2*2*3*59*61*97*416510539*72330832279)==int("68656c6c6f20776f726c64", 16)

Any type of mathematical equations could be used, such as: powers, series, factorials, and other mathematical operations.
The rules:

You may select your own way to encode/represent "hello world" as an integer. Hash functions are also allowed
Mathematical libraries (e.g. numpy, GMP) are allowed.
The intention is to focus on the mathematics part

What is the winning criterion?

@Victor The most creative/ingenious   equation

Creativity is not objective. Are you thinking of [tag:popularity-contest]?

Any integer can represent "hello world" if you are allowed to decide the encoding. e.g. -1 = "hello worlc", 0 = "hello world", 1 = "hello worle", etc.

@KendallFrey I added an answer exploiting what you are saying just to show that.

@kylek Since you did not specified the exact winning criteria beyond "the most creative/ingenious", i took the liberty to add the [tag:popularity-contest] as the winning criterion.

(in the context of this website) all computer data and programs can be trivially represented as numbers - because that's the model the inventors (Babbage, et al) used. Also allowing any encoding really just makes this a contest of who can write the most creative program that yields a number. There is an implication that the source code should use "mathematical operations", but anything a program does can be modeled as a math op. Suggest you require ASCII encoding and then make the contest about representing it as a "special number" See: http://www2.stetson.edu/~efriedma/numbers.html

Shouldn't the function by which a number is produced by "hello world" be invertible, such that, if you receive the number and apply the inverse, "hello world" is output?

@DavidCarraher yes it should

You are playing extremely fast and loose with your mathematical terminology. You are using "equation" and "function" seemingly interchangeably. I think the word you were looking for is "expression". But even then, the question is not well posed. The mathematical encoding for "hello world" I choose for mine is the original K&R hello world source code. Oh, hey, it works!

@Tim I am also a little bit confused about the proper way to describe my question.

Here's a guy who wrote an actual mathematical formula where f(0)='H', f(1)='e' etc. http://www.stavros.io/posts/printing-hello-world-using-curve-fitting/

@user2460798 link to Erich Friedman's pages about special numbers is now https://erich-friedman.github.io/numbers.html

Python 2.7
Some abuse of the random number generator, works on Python 2.7 but not Python 3.x since the generator seems to have changed the seeding algorithm;
>>> import random
>>> n=[(15,30,15,25,15,0,-15,-25,-15,-30,-15),(107,35,34,26,22,0,71,188,94,64,81)]
>>> random.seed(4711)
>>> m = zip("MERRY CHRISTMAS",*n)
>>> print(''.join(map(lambda x:chr(ord(x[0])+random.randint(x[1],x[2])),m)))

hello world

This made me laugh out loud at my desk. People are staring at me right now :-/

I'll do better than just printing it, I'll print it infinitely many times!
The rational number
1767707668033969 / 3656158440062975

returns the following base-36 expansion:
0.helloworldhelloworldhelloworldhelloworldhelloworld...

Try it out! (Wolfram Alpha)
Or, if you want a more subliminal message, try:
2399843759207982499621172523113947162810942763812298565948669
/ 1357602166130257152481187563160405662935023615

Which returns (again in base 36):
helloworld.helpimtrappedinanumberfactoryhelpimtrappedinanumberfactoryhelpimtrappedinanumberfactory...

If your program worked with only integers, you'd never see the fractional part.

Python (not finished... yet!) finished! :D
number = ((sum(b'This text will end up converting to the text "hello world" by a bunch of math.') *
sum(b'For example, multiplication will be used to increase the number so that it may reach the required result.') *
sum(b'Wow, double multiplication! The required result number is extremely big so I have to use lots of math to get there.') *
sum(b'TRIPLE multiplication?!?!?! Wow!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Did I put too many exclamation points?') *
sum(b'I think maybe I might have put too many exclamation points, oops. :(') *
sum(b'This is taking a long time...') *
sum(b'A very, very, very long time...')) // 2)

number -= (sum(b'Okay, the number is a bit too high. Blah. This is extremely hard.') *
sum(b'I need to reduce it. I will just keep multiplying again! Yay! That seems effective!') *
sum(b'I don\'t know what to write now... I used up all my creativity in the previous number.') *
sum(b'So. Uhhh, how has your day been? Was it good? I wonder how many people are still reading.') *
sum(b'Gah! There is nothing to type about anymore! I will just type randomness then.') *
sum(b'Do you like pie? I like pie. Refrigerator. The chicken ate the potato. Llamas are not tasty.'))

number -= (sum(b'Blah, I am still a tiny bit too high!') *
sum(b'This is very frustrating!') * sum(b'Argh!!!!!!!') *
sum(b'I have even less creative ideas now since I have written two paragraphs already.') *
sum(b'Well, I suppose they\'re not paragraphs. They\'re just blocks of code.') *
sum(b'The only reason I made that remark was to increase this number to subtract, so that I reach my target.'))

number -= (sum(b'I am an extremely miniscule amount over the target!!!') *
sum(b'I am so close!!! So close!!') *
sum(b'I must make it!!! I will!!!') *
sum(b'I shall NEVER give up!!!') *
sum(b'Okay, ummm... maybe not exactly "never"...') *
sum(b'I mean, this is REALLY hard...'))

number -= (sum(b'I am so close. This is just ridiculous.') *
sum(b'Just ridiculous. And that\'s awesome :D') *
sum(b'Why am I doing this?!?') *
sum(b'The answer\'s probably "becase I can."') *
sum(b'Notice how most of the text in this program is meaningless.'))

number -= (sum(b'How have I been above my target this whole time? That is very odd.') *
sum(b'I wonder how much time I could have saved if I removed a few characters in the first block.') *
sum(b'I wish I did that. That would have made it so much easier.... But oh well.') *
sum(b'Well, I am really really really really really really close now!'))

number -= (sum(b'I am so close!') *
sum(b'I will never give up now! Not after all this!') *
sum(b'I wonder if I will ever get exactly on the target. What if I do, and then discover a typo? :O') *
sum(b'So close!'))

number -= (sum(b'Wow; this is the eighth block. That\'s a lot of blocks!') *
sum(b'I only have a little more to go! I must finish! I will!') *
sum(b'It is starting to get harder thinking of things to type than it is getting to the target...'))

number -= (sum(b'These strings are short') *
sum(b'So the number to subtract is less') *
sum(b'Hi'))

number += (sum(b'Finally adding') *
sum(b'That\'s new') *
sum(b':D'))

number -= (sum(b'I am back to subtraction, and also longer strings.') *
sum(b'But this time I only get two strings!'))

number -= (sum(b'I have switched over to adding the strings, not multiplying them!') +
sum(b'I am really really close! So close that I can\'t even multiply two strings to subtract anymore!') +
sum(b'This is very exciting; I\'ve nearly made it! Only a few more strings to add...') +
sum(b'I ran out of ideas for what to type again... I will just type exactly what I am thinking, which is what I am doing now actually.') +
sum(b'But now the only thing I am thinking about is getting to the target, and there is not much about that to type...') +
sum(b'I am only a few thousand away!!!!!!!!!!!!'))

number += 8 # NOOOOOOOOOOOOOOOOOOOOOOOOOOOOO

print(number)

Outputs 126207244316550804821666916 (equivalent to your example, 0x68656c6c6f20776f726c64)

You have a good understand of what I am asking.

"Llamas are not tasty" haha +1

This should win.

You may select your own way to encode/represent "hello world" as an integer.

Well, then...
PHP
<?=1?>

where 1 represents "hello world" because I said so.

10 in base-"hello world"

Calculator Font / FreePascal
I may get into trouble for posting this, but I'll do it anyway :-)

Calculate 7734/100000. Change the leading zero to blue, and the other digits to calculator font. Turn it upside down. The blue O represents the world:

If that's too lazy, how about this:
uses graph;
var gd, gm : integer;
var n,m:integer;

begin
  gd := D4bit;
  gm := m640x480;
  initgraph(gd,gm,'');
  setcolor(black);

  For n:=0 to 5  do for m:=0 to 3 do begin;
    setfillstyle(solidfill,(abs(n*2-1)));

    if(($967EEF shr (20-n*4+m)) and 1) = 1
      then sector(50+n*80,100,90*m,90*(m+1),40,60);

    if(($EDF7E9 shr (20-n*4+m)) and 1) = 1
      then sector(50+n*80,300,90*m,90*(m+1),40,60);
    end;

  readln;
  closegraph;
end.

circles numbered 0-5, colour determined by abs(2n-1). One hex digit per circle, quadrants coloured from most significant bit downwards, clockwise from bottom right. By the mystic constants 967EEF and EDF7E9 hex.
Special thanks to the following primitive, and to Borland for putting it in TurboPascal so that FreePascal could clone it.
procedure Sector(
x: SmallInt;
y: SmallInt;
StAngle: Word;
EndAngle: Word;
XRadius: Word;
YRadius: Word
);
Sector draws and fills a sector of an ellipse with center (X,Y) and radii XRadius and YRadius, starting at angle Start and ending at angle Stop.

I have not thought of this method before, Good thinking out of the box!

Ruby & Python
Using base 36 math, we arrive at an integer representation quite easily in Ruby & Python:

Ruby
%w(hello world).map{|n|n.to_i(36)}

result:
[29234652, 54903217]

or, expressed as a general function:
def f(words); words.split.map{|n|n.to_i(36)}; end

example:
f("hello world")
=> [29234652, 54903217]

Python
def f(words): return map(lambda n: int(n,36), words.split())

example:
>>> f("hello world")
[29234652, 54903217]

Some carefully crafted PHP:
$x=18306744;
$w=($z=($y=30)/3)/2;
echo base_convert($x, $z, $y+$z/$w),chr($y+$z/$w).base_convert($x*($y/$z)-$w*41*83,$z,$y+$y/$w);

This is a good answer, It is the kind of answer I was looking for.

R6RS Scheme
#!r6rs
(import (rnrs))
(define (hello-world)
  (bitwise-xor (fold-left (lambda (acc d)
                        (+ (* acc 256)
                           (+ (bitwise-and 255 acc) d)))
                      104
                      '(-3 7 0 3 8 0 -8 3 -6 -8))
               (bitwise-arithmetic-shift 87 40)))

Outputs #x68656c6c6f20776f726c64 (in decemal):
126207244316550804821666916

My original implementation was:
Racket (Scheme dialect)
(define (hello-world)
  (bitwise-xor (foldl (lambda (d acc)
                        (+ (* acc 256)
                           (+ (bitwise-and 255 acc) d)))
                      104
                      '(-3 7 0 3 8 0 -8 3 -6 -8))
               (arithmetic-shift 87 40)))

JavaScript
function stringTheory(theory) {
  var proof = 0;
  var principles = theory.split(/[ ,.'-]/);
  for (var i = 0; i < principles.length; i++) {
      var formula = '';
      for (var j = 0; j < principles[i].length; j++) {
        formula += principles[i].charCodeAt(j).toString(10);
      }
      proof += +formula;
  }
  return proof;
}

console.log(
/* \2 and \3 are start of text and end of text characters */
stringTheory('\2 Yo it\'s 4327 - Go to space, look back, and see the dot of a small blue rock you once sat on amid the vast empty void - KA-BOOM - you are in awe of it. "Ah" - so tiny in this vast space yet you are even more so. A mere atom in an ocean of stars, the earth a speck of dust to the sun\'s ping-pong ball. One day you shall go back and as your toes touch the soft soil once more, the cool wind in your hair as you cast your gaze upon the moon, a mere rock just like this one, and bask in it\'s warm glow - Ah. Only then can you know the scale of it all, what luck you have to call this place home.  And with this new ken, a love you\'ve kept for all of time but had not seen - for it is clear to you now. You lay open your arms and fill the air with your song - (aah) ~o Good-bye space and ... o? \3') + 42
);

What is going on?
We take this string and apply a little stringTheory() (it is actually a transmission from the future):
'\2 Yo it\'s 4327 - Go to space, look back, and see the dot of a small blue rock you once sat on amid the vast empty void - KA-BOOM - you are in awe of it. "Ah" - so tiny in this vast space yet you are even more so. A mere atom in an ocean of stars, the earth a speck of dust to the sun\'s ping-pong ball. One day you shall go back and as your toes touch the soft soil once more, the cool wind in your hair as you cast your gaze upon the moon, a mere rock just like this one, and bask in it\'s warm glow - Ah. Only then can you know the scale of it all, what luck you have to call this place home.  And with this new ken, a love you\'ve kept for all of time but had not seen - for it is clear to you now. You lay open your arms and fill the air with your song - (aah) ~o Good-bye space and ... o? \3'
First we split it at its punctuation to form words. We then create a set of numbers by converting the characters to their decimal ASCII code. Adjoined letters become adjoined numbers (e.g. aa becomes 9797).
The numbers are then summed. What we get back is 191212222216169 an utterly useless number, it has no meaning, much like the quadrillions of rocks that float idly in space. What makes this world special? Why it is life. So by giving this number the meaning of life +=42 then we get 191212222216211;
But why?
What does this mean? Why it means stringTheory("Hello world") of course.

Python
from math import fsum
c=[104.,-4412.705557362921,12008.518259002305,-13041.051140948179,7566.060243625142,-2619.91695720304,567.427662301322,-77.52280096313,6.48776455347,-0.303552138602,0.006079144624]
def f(x):
    return fsum([c[i]*x**i for i in range(len(c))])
s=""
for i in range(11):
    s+=chr(int(round(f(i))))
print s

Ruby
Any string is mapped to an integer.
# encode string to integer
def str_to_int(s)
  i = 0
  s.chars.each do |c|
    i = i << 7 | c.ord
  end
  i
end

The inverse function:
# decode integer to string
def int_to_str(i)
  s = ''
  while i > 0 do
    s = (i & 0x7f).chr + s
    i = i >> 7
  end
  s
end

Examples:
str_to_int("ABC")
=> 1073475
int_to_str(1073475)
=> "ABC"

str_to_int("hello world")
=> 123720932638399026476644
int_to_str(123720932638399026476644)
=> "hello world"

C#
A method to convert any string (hello world or something else) to hexadecimal string
string Encode(string text)
{
   string hexValue = String.Empty;
   foreach(char c in text)
      hexValue += String.Format("{0:X}", (int)c);
   return hexValue;
}

A method to convert hexadecimal string to string
string Decode(string hexValue)
{
   string text = String.Empty;
   for (int i = 0; i < hexValue.Length; i += 2)
   {
     int value = Convert.ToInt32(hexValue.Substring(i, 2), 16);
     text += (char)value;
   }
   return text;
}

Here goes the complete C# program
using System;

namespace ConsoleApplication1
{
    class Program
    {

        static string Encode(string text)
        {
            string hexValue = String.Empty;
            foreach(char c in text)
                hexValue += String.Format("{0:X}", (int)c);
            return hexValue;
        }

        static string Decode(string hexValue)
        {
            string text = String.Empty;

            for (int i = 0; i < hexValue.Length; i += 2)
            {
                int value = Convert.ToInt32(hexValue.Substring(i, 2), 16);
                text += (char)value;
            }

            return text;
        }

        static void Main(string[] args)
        {
            string Text1 = "Hello World!";
            Console.WriteLine("Before Encoding: " + Text1 + "\n");

            string Hex = Encode(Text1);
            Console.WriteLine("After endoding: " + Hex + "\n");

            string Text2 = Decode(Hex);
            Console.WriteLine("After decoding: " + Text2 + "\n");
        }
    }
}

And here is the output.

Python
def D(A):
    try:
        return sum(D(x)**2 for x in A)
    except TypeError:
        return A
print hex(D([[[[33,22,3,1],[20,13,2],5],[[31,19,1],[11,5,3],1]],[[[26,13],[18,14,6,4],1],[[12,10],[10,3,1],2],4],28]))

Recursively decomposes the target number into sums at most four squares.  My base case is <100.  I used http://www.alpertron.com.ar/FSQUARES.HTM to calculate the decompositions.
(Maybe a base case of <=1 would have been interesting...)

Python
def church(i):
    if i > 0:
        return 'f(' + church(i-1) + ')'
    else:
        return 'x'

def church_string(bs):
    import base64
    return church(int(base64.b16encode(bs), 16))

print(church_string(b'hello world'))

The result really is a number, I swear!

Just a little C fun with numbers, nothing special.
int main()
{
    int a , b, c;
    double i = 0, f = 0;

    for (; i < 1; i += .00000012785666)
        f += cos(i);
    c = f;
    a = f * 276.393089;
    b = a + f * 7.4358109;

    printf("%.4s%.4s%.4s\n", &a, &b, &c);
}

demo

(+ 110145154154157040127157162154144 0)

This is Lisp, I take it?

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


text:
Thinking outside the box
You are trying to fit a sphere into a 5-sided box, but sometimes it does not fit completely. Write a function to calculate how much of the sphere is outside (above the rim of) the box.
There are 3 possible situations:

The sphere fits completely in the box. The answer will be 0.
The sphere sits on the rim of the box. The answer will be more than half of the total volume.
The sphere sits on the bottom of the box.

You can see each situation here:

You must write a program or function to compute this value to at least 4 significant digits.
Input: 4 non-negative real numbers in whatever format is convenient* - width, length, depth of the box (interior measurements), and diameter of the sphere.
Output: 1 non-negative real number in a usable format* - the total volume (not the percentage) of the sphere outside the box.
* must be convertible to/from a decimal string
You are encouraged to limit your use of trigonometry as much as possible.
This is a popularity contest, so think outside the box!

any example cases please?

Can we assume either the walls of the box are infinitely thin or the dimensions given are interior dimensions? :)

What are the maximum values for the inputs?

@DarrenStone I think that the walls thickness are uninportant. You could consider it infinite as well, so the box would be a rectangular hole in an infinte block. The result would be the same as any other value for the wall thickness. Except if you are intending to bend/cheat the rules by physically breaking, distorting or slicing either the box or the sphere, or do something really strange.

@Victor, the thickness is unimportant only if the dimensions given are interior dimensions. Thus, my question. :)

@DarrenStone The boxes only have thickness for the purposes of a nice picture. The problem deals with interior dimensions.

@Blender Whatever the limits of your number representation are. You shouldn't depend on them being less than a specific value.

@mniip I posted some example code with output.

It's not clear whether you're asking for the volume of the part of the sphere which is outside the box, or the proportion as a fraction of the sphere's volume.

Forth
Please find, below, a sphere outside the box.
The "sphere" is the volume-computing function f. The reference test cases compose the "box".
                     ( x y z d -- v )
                 : f { F: z F: d } d f2/
              { F: r } fmin { F: m } m f2/ {
             F: b } d m f<= d z f<= and if 0e
             else r r r f* b b f* f- fsqrt f-
              { F: t } d m f<= t z f> or if d
               z f- else d t f- then r 3e f*
                  fover f- pi f* fover f*
                      f* 3e f/ then ;

                     1e                 1e
                     1e                 1e
                     f                  f.
            cr       1e        1e       0e
            1e       f         f.       cr
            1e       1e 0.5e 1e f f. cr 1e
            0.999e 1e          1e     f
            f.  cr            0.1e 1e
            1.000e 0.500e f f. cr

Output:
0.
0.523598775598299
0.261799387799149
0.279345334323962
0.0654299441440212

Java - integer based
This program does not use pi and does not call any external function - not even sqrt. It only uses simple arithmetic - +, -, * and /. Furthermore, other than a scaling step, it works exclusively with integers. It basically divides the sphere into little cubes and counts the ones that are outside the box.
public class Box {
    private static final int MIN = 10000;
    private static final int MAX = MIN * 2;

    private static final int[] SQ = new int[MAX * MAX + 1];

    static {
        int t = 1;
        for (int i = 1; i <= MAX; ++i) {
            while (t < i * i) SQ[t++] = i - 1;
        }
        SQ[MAX * MAX] = MAX;
    }

    public static long outsideInt(int r, int w, int z) {
        int r2 = r * r;
        int o = z - r + 1;
        if (w < r * 2) {
            int t = 1 - SQ[r2 - w * w / 4];
            if (t < o) o = t;
        }
        long v = 0;
        for (int i = o; i <= r; ++i) {
            int d = r2 - i * i;
            int j0 = SQ[d];
            v += 1 + 3 * j0;
            for (int j = 1; j <= j0; ++j)
                v += 4 * SQ[d - j * j];
        }
        return v;
    }

    public static double outside(double x, double y, double z, double d) {
        double f = 1;
        double w = x < y ? x : y;
        double r = d / 2;
        while (r < MIN) {
            f *= 8;
            r *= 2;
            w *= 2;
            z *= 2;
        }
        while (r > MAX) {
            f /= 8;
            r /= 2;
            w /= 2;
            z /= 2;
        }
        return outsideInt((int) r, (int) w, (int) z) / f;
    }

    public static void main(final String... args) {
        System.out.println(outside(1, 1, 1, 1));
        System.out.println(outside(1, 1, 0, 1));
        System.out.println(outside(1, 1, 0.5, 1));
        System.out.println(outside(1, 0.999, 1, 1));
        System.out.println(outside(0.1, 1, 1, 0.5));
    }
}

Output:
0.0
0.5235867850933005
0.26178140856157484
0.27938608275528054
0.06542839088004015

In this form, the program requires more than 2GB memory (works with -Xmx2300m here) and is prettty slow. It uses the memory to precalculate a bunch of square roots (arithmetically); it's not really necessary, but without that it would be a LOT slower. To improve both memory needs and speed, reduce the value of the MIN constant (that will decrease the accuracy though).

Python 2 (Array-based approach)
It creates an array of arrays with truth-values if a specific square in that grid is inside the circle or outside the circle. It should get more precise the bigger the circle is you draw. It then selects either an area below or above a certain row and counts the amount of squares that belongs to the circle and divides that by the amount of squares that are in the entire circle.
import math as magic
magic.more = magic.pow
magic.less = magic.sqrt

def a( width, length, depth, diameter ):
  precision = 350 #Crank this up to higher values, such as 20000

  circle = []
  for x in xrange(-precision,precision):
    row = []
    for y in xrange(-precision,precision):
      if magic.less(magic.more(x, 2.0)+magic.more(y, 2.0)) <= precision:
        row.append(True)
      else:
        row.append(False)
    circle.append(row)

  if min(width,length,depth) >= diameter:
    return 0
  elif min(width,length) >= diameter:
    row = precision*2-int(precision*2*float(depth)/float(diameter))
    total = len([x for y in circle for x in y if x])
    ammo = len([x for y in circle[:row] for x in y if x])
    return float(ammo)/float(total)
  else:
    #Why try to fit a sphere in a box if you can try to fit a box on a sphere
    maxwidth = int(float(precision*2)*float(min(width,length))/float(diameter))
    for row in xrange(0,precision*2):
      rowwidth = len([x for x in circle[row] if x])
      if rowwidth > maxwidth:
        total = len([x for y in circle for x in y if x])
        ammo = len([x for y in circle[row:] for x in y if x])
        return float(ammo)/float(total)

Python 2.7, Spherical Cap Formula
This version will throw a runtime warning in some cases, but still outputs the correct answer.
import numpy as n
x,y,z,d=(float(i) for i in raw_input().split(' '))
r=d/2
V=4*n.pi*r**3/3
a=n.sqrt((d-z)*z)
b=min(x,y)/2
h=r-n.sqrt(r**2-b**2)
c=lambda A,H: (3*A**2+H**2)*n.pi*H/6
print(0 if d<=z and r<=b else c(a,d-z) if r<=b and z>r else V-c(a,z) if r<=b or z<h else V-c(b,h))

For 11 characters more, I can get rid of the warning.
import math as m
x,y,z,d=(float(i) for i in raw_input().split(' '))
r=d/2
V=4*m.pi*r**3/3
if d>z:
    a=m.sqrt((d-z)*z)
b=min(x,y)/2
h=r-m.sqrt(r**2-b**2)
c=lambda A,H: (3*A**2+H**2)*m.pi*H/6
print(0 if d<=z and r<=b else c(a,d-z) if r<=b and z>r else V-c(a,z) if r<=b or z<h else V-c(b,h))

Here are the test cases run on version 1:
$ python spherevolume.py
1 1 1 1
0
$ python spherevolume.py
1 1 0 1
0.523598775598
$ python spherevolume.py
1 1 .5 1
0.261799387799
$ python spherevolume.py
1 .999 1 1
0.279345334324
$ python spherevolume.py
.1 1 1 0.5
spherevolume.py:65: RuntimeWarning: invalid value encountered in sqrt
  a=n.sqrt((d-z)*z) or b
0.065429944144

Even though this isn't code golf, you can shorten import numpy as n to from numpy import* and take away all of the n. in your code.

@Timtech Thanks for the heads up and suggestion.

Mathematica
Using numerical integration with proper limits.
f[width_, length_, height_, diam_] :=
 With[{r = diam/2, size = Min[width, length]/2},
  Re@NIntegrate[
    Boole[x^2 + y^2 + z^2 < r^2], {x, -r, r}, {y, -r, r},
      {z, -r, Max[-r, If[size >= r, r - height, Sqrt[r^2 - size^2]]]}]
  ]

Reference Implementation - C#
using System;

namespace thinkoutsidethebox
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(OutsideTheBox(1, 1, 1, 1));
            Console.WriteLine(OutsideTheBox(1, 1, 0, 1));
            Console.WriteLine(OutsideTheBox(1, 1, 0.5, 1));
            Console.WriteLine(OutsideTheBox(1, 0.999, 1, 1));
            Console.WriteLine(OutsideTheBox(0.1, 1, 1, 0.5));
        }

        static double OutsideTheBox(double x, double y, double z, double d)
        {
            x = Math.Min(x, y);
            double r = d / 2; // radius
            double xr = x / 2; // box 'radius'
            double inside = 0; // distance the sphere sits inside the box
            if (d <= x && d <= z) // it fits
            {
                return 0;
            }
            else if (d <= x || r - Math.Sqrt(r * r - xr * xr) > z) // it sits on the bottom
            {
                inside = z;
            }
            else // it sits on the rim
            {
                inside = r - Math.Sqrt(r * r - xr * xr);
            }
            // now use the formula from Wikipedia
            double h = d - inside;
            return (Math.PI * h * h / 3) * (3 * r - h);
        }
    }
}

Output:
0
0.523598775598299
0.261799387799149
0.279345334323962
0.0654299441440212

I do not understand these results. The first one is obviously 0. The second one has no height, so that one should be 1. The third one can house the ball, and exactly half of it is above it (answer should be 0.5). The box in case 4 is just a little to small, so it rests on top of the box. The answer should be a little bit more than 0.5. The answer for the last one should be >0.5, as the width/length is not sufficient to fit the ball inside.

@Sumurai8 "Output: the total volume (not the percentage) of the sphere outside the box."

Ruby
Let's see...
If the box is fully inside, then width>diameter; length>diameter and height>diameter.
That should be the 1st check to run.
If it's sitting at the bottom, then w>d ; l>d and h
V=(pi*h^2 /3)*(3r-h) So in that case, We just get the height and run it through that.
If it's stuck, we use a similar formula (V=(pi*h/6)*(3a^2 + h^2)). In fact our earlier formula is based on this one! Essentially, we use that, and a is simply the smaller one of w and l. (hint, we can get height by doing h=r-a)
Now the code!
def TOTB(wi,le,hi,di)
  if wi>=di and le>=di and hi>=di
    res = 0
  elsif wi>=di and le>=di
    r = di/2
    res = 3*r
    res -= hi
    res *= Math::PI
    res *= hi*hi
    res /= 3
  else
    r = di/2
    if wi>le
      a=le
    else
      a=wi
    end #had issues with the Ternary operator on ruby 2.2dev
    h = r-a
    res = 3*a*a
    res += h*h
    res *= Math::PI
    res *= h
    res /= 6
  end
  res
end

Note** I didn't test it too much, so an error may have crept in, if anyone notices one, do tell!
The math is solid though.
Shorter version:
v1 = ->r,h{(3*r -h)*Math::PI*h*h/3}
v2 = ->r,a{h=r-a;((3*a*a)+(h*h))*h*Math::PI/6}
TOTB = ->wi,le,hi,di{(di<wi&&di<le&&di<hi)?0:((di<wi&&di<le)?v1[di/2,hi]:v2[di/2,((wi>le)?le:wi)])}

(Now I know for sure that getting h for v2 is done differently, but I'll fix it later.

Nice. That code reads clearly. But are you sure about the following statement?  "we can get height by doing h=r-a"  I was just reading up on the spherical cap formulae, and the diagram doesn't suggest a relationship so simple. I'll give it another read.

@DarrenStone Now that I look back I'm not sure. I'm extraordinarily down/exhausted, but either way, it's very easy to patch!

I'm almost sure a = wi > le ? le : wi should work. Otherwise, you have a bug.

a = wi>le?le:wi did not work. I'm guessing it's because I'm running git ruby (2.2 developer), it might have said imbalance.

c++
#define _USE_MATH_DEFINES   //so I can use M_PI
#include <math.h>           //so I can use sqrt()
#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
    double w;
    double l;
    double d;
    double sd;
    double min_wl;
    double pdbd;
    double sl;
    cin >> w >> l >> d >> sd;

    min_wl = min(w, l);
    if(sd <= min_wl)
    {
        pdbd = 0.0;
    } else
    {
        pdbd = (sqrt((((sd/2)*(sd/2))-((min_wl/2)*(min_wl/2)))) + (sd/2));
    }
    sl = sd - d;

    if(sd <= min(min_wl, d))
    {
        cout << 0;
        return 0;
    } else if((sl < pdbd) && (pdbd > 0.0))    //sits on lip of box
    {
        cout << (M_PI * (((sd/2) * pdbd * pdbd) - ((pdbd * pdbd * pdbd)/(3))));
        return 0;
    } else                  //sits on bottom of box
    {
        cout << (M_PI * (((sd/2) * sl * sl)-((sl * sl * sl)/(3))));
        return 0;
    }
    return 0;
}

My code finds the volume of the solid of rotation of the graph of some portion of a half-circle.  pdbd holds the linear distance of the projection of a point on the surface of the sphere that touches the lip of the box to the diameter of the sphere that, if extended, would be normal to the bottom of the box.  The two expressions that contain M_PI are basically the anti-derivative of the integral of pi * -(x^2)+2rx with respect to x (where x is a measure of the length along the above mentioned diameter through the sphere and where r is the radius of the sphere) evaluated at either pdbd or the difference of the sphere diameter and the box depth depending on the particular case that occurs with the different dimensions.


text:
Can you cancel the stackoverflow exception in the following code?
The following code will produce a run-time error, stackoverflow exception.
class Foo
{
    //static Foo foo = new Foo(); // you are not allowed using this approach
    //static readonly Foo foo = new Foo(); // you are not allowed using this approach
    Foo foo = new Foo();
}
class Program
{
    static void Main(string[] args)
    {
        new Foo();
    }
}

The objective is to cancel the exception without

removing, modifying or commenting out the existing code,
using the approaches mentioned (and their variants in access modifiers, public, private, etc) as the given comments,
using try-catch-finally or its variants,
using attributes,
using compilation condition,

You are only allowed to add your own code inside the Foo class. How do you cancel the exception at run-time?

It would be best to tag this question as either [tag:popularity-contest] or [tag:code-golf] so it's clear how you will objectively declare a winner.

I probably will add more rules if your ideas are too trivial. Sorry for this inconvenience.

Pulling the rug out like that may be considered rude. It's best to think your question through thoroughly before asking the internet to spend effort on it. :-)

This is a [tag:popularity-contest] yet the accepted answer has few votes. You should accept the highest-voted answer (see [tag:popularity-contest])

@Quincunx: I changed the tag.

You need winning criterion (?)

Never wrote C# before, does this work ?
class Foo
{
    Foo fooExit = exitMe();
    //static Foo foo = new Foo(); // you are not allowed using this approach
    //static readonly Foo foo = new Foo(); // you are not allowed using this approach
    Foo foo = new Foo();

    static Foo exitMe()
    {
        System.Environment.Exit(0);
        return null;
    }
}
class Program
{
    static void Main(string[] args)
    {
        new Foo();
    }
}

Well, the rules forbid "using attributes".

@Victor: The code above does not contain any attributes.

@StiffJokes Interesting. I am from Java and never programmed in C#. In Java the Foo fooExit = exitMe(); would be a declaration of an attribute called fooExit. I.E. For me attribute and field were synonyms. Googling this, it looks like that in C# attributes are more-or-less what in java are called annotations. Thank you, did not knew this!

I changed the tag just for attracting more creative method. :-)

The winner might be different from the accepted  answer. It does not matter for me.

foo must be declared after fooExit to make the trick work.

As I see it, this does not cancel the exception but exit the program, before it is thrown. Does that really count?

Here, another try:
class Foo
{
    //static Foo foo = new Foo(); // you are not allowed using this approach
    //static readonly Foo foo = new Foo(); // you are not allowed using this approach
    Foo foo = new Foo();
    MWAHAHAHA, THIS LINE GIVES A COMPILE ERROR! NO STACKOVERFLOW EXCEPTION ANYMORE! LOL
}
class Program
{
    static void Main(string[] args)
    {
        new Foo();
    }
}

It is really funny, really.

That's what I was gonna do...

How about this?
class Foo
{
    //static Foo foo = new Foo(); // you are not allowed using this approach
    //static readonly Foo foo = new Foo(); // you are not allowed using this approach
    String str = @"
    Foo foo = new Foo();
    ";
}
class Program
{
    static void Main(string[] args)
    {
        new Foo();
    }
}

class Foo
{
    public class Bar
    {
        Foo foo = new Foo();
    }
}
class Program
{
    static void Main(string[] args)
    {
        new Foo();
    }
}

I don't have a C# compiler at hand, but I suspect this might work. The idea is to put the definition in a nested class, such that foo would only be assigned if an instance of Bar is created. Now, the problem is that (I believe) the nested class needs to be public. I don't know if this is a rule violation, i.e. that the rule applies to any use of an access modifier, or only if applied to foo. (Could someone who can compile C# please try this with and without the public?)

Works with and without public. You also could've tested this on an online compiler, e.g. ideone.

class Foo
{
    Foo(bool recursion = false)
    {
        if (recursion)
            Foo foo = new Foo();
    }
}
class Program
{
    static void Main(string[] args)
    {
        new Foo();
    }
}

To simplify Florent's code:
class Foo
{
    Foo foo = new Foo();

    static Foo() {
        System.Environment.Exit(1);
    }

}

Does this actually work? Won't Foo foo = new Foo(); be (recursively) evaluated before any constructor is executed?

@nitro2k01 No, it won't. The static ctor is executed before any instance member initialization.

class Foo
{
    while (true);
    Foo foo = new Foo();
}
class Program
{
    static void Main(string[] args)
    {
        new Foo();
    }
}

Its not a bug, it's a feature!
In case that doesn't work
class Foo
    if(false)
        Foo foo = new Foo();
}

class Program
{

    static void Main(string[] args)
    {
        new Foo();
    }
}

I guess that stopping stack overflow from happening by making infinite loop prior to it counts. It doesn't appear to be disallowed.

@xfix Indeed.
Since the problematic code will never be executed, it cannot cause a lockup.
Aka: You cannot lock me up because I'll lock me up first :-P

I can't see how that would compile in C#. I'm getting a Invalid token 'while' in class, struct, or interface member declaration compiler error with your code.

@Mark - Hmmm, seems a little passive-aggressive... ;) I like it.

@simon It's called c-SHARP, because its not for the soft-hearted :-P

The Answer is:
class Foo
{
    //static Foo foo = new Foo(); // you are not allowed using this approach
    //static readonly Foo foo = new Foo(); // you are not allowed using this approach

    public void Method()
    {
    Foo foo = new Foo();
    }
}
class Program
{
    static void Main(string[] args)
    {
        new Foo();
        Console.ReadLine();
    }
}

 Note: The rules changed since I posted this.
That is it:
class Foo
{
    //static Foo foo = new Foo(); // you are not allowed using this approach
    //static readonly Foo foo = new Foo(); // you are not allowed using this approach
    Foo foo = null; // Removing code != modifying.
}
class Program
{
    static void Main(string[] args)
    {
        new Foo();
    }
}

It is almost funny, just almost. :-)

Your trivial code can actually be simplified as Foo foo; to make it almost funnier.

@StiffJokes In this case, you could argue that I was deleting code, against the rules (as they were at that time).

class Foo
{
    //static Foo foo = new Foo(); // you are not allowed using this approach
    //static readonly Foo foo = new Foo(); // you are not allowed using this approach
    Foo foo = true?null: new Foo();
}
class Program
{
    static void Main(string[] args)
    {
        new Foo();
    }
}


text:
Sorting a List with a Another Sorted List
Say i have a list (unorder):
Score = ['score1','score10','score6','score2','score22','score12']
Names = ['name1','name10','name6','name2','name22','name12']
email = ['email1','email10','email6','email2','email22','email12']

and then Score is sorted to be
ScoreSorted = ['score1','score2','score6','score10','score12','score22'].

The shortest code (in byte) to sort Name and Email with Score list wins
result of email and names list should be
EmailSorted = ['email1','email2','email6','email10','email12','email22'].
NamesSorted = ['name1','name2','name6','name10','name12','name22'].

It's not clear whether you're expecting ScoreSorted to be input, output, or neither.

So, we have a list A, and a list A' which is a permutation of A, and then for a given list B we should find the same permutation B'?

@marinus I interpretted the problem as the following: given a list A with a logical lexicographical ordering, sort this list, and apply the same permutation to both B and C. This is analogous to sorting data rows in a spreadsheet by a specific column.

Ruby 81 bytes
m=Score.each_index.sort_by{|i|Score[i]}
p m.map{|i|Names[i]}
p m.map{|i|Email[i]}

A golfed implemention of the algorithm below, assuming Score, Names, and Email are all already defined, and that only output of the post-sorted Names and Email is required.
Sample usage:
Score = ['score1','score10','score6','score2','score22','score12']
Names = ['name1','name10','name6','name2','name22','name12']
Email = ['email1','email10','email6','email2','email22','email12']

m=Score.each_index.sort_by{|i|Score[i]}
p m.map{|i|Names[i]}
p m.map{|i|Email[i]}

Sample output:
["name1", "name10", "name12", "name2", "name22", "name6"]
["email1", "email10", "email12", "email2", "email22", "email6"]

Ruby (with natural sort) 123 bytes
m=Score.each_index.sort_by{|i|Score[i].scan(/\d+|\D+/).map{|i|i=~/\d/?i.to_i: i}}
p m.map{|i|Names[i]}
p m.map{|i|Email[i]}

Correctly sorts strings with any number of digital groupings, as one would sort them 'naturally'. The only caveat is that all strings in the Score array must start with a digit, or all must start with a non-digit.
Sample output:
["name1", "name2", "name6", "name10", "name12", "name22"]
["email1", "email2", "email6", "email10", "email12", "email22"]

Python
Not a code-golf answer.

Find the inverse permutation of the list which is to be sorted in lexicographical order (in the problem description, this Scores array). This can be achieved in O(n log n) time (as the problem is analog to sorting), although the implementation below is O(n²).
Apply this permutation to each list. The permute function is O(n) complexity.

Sample implementation:
def get_inv_perm(items):
  size = len(items)
  perm = [0]*size
  for i in range(size):
    for j in range(size): perm[j] += items[j] > items[i]
  return perm

def permute(arr, perm):
  size = len(arr)
  out = [0] * size
  for i in range(size):
    val = perm[i]
    out[i] = arr[val]
  return out

if __name__ == "__main__":
  Score = ['score1','score10','score6','score2','score22','score12']
  Names = ['name1','name10','name6','name2','name22','name12']
  Email = ['email1','email10','email6','email2','email22','email12']

  perm = get_inv_perm(Score)

  print permute(Score, perm)
  print permute(Names, perm)
  print permute(Email, perm)

Sample output:
['score1', 'score10', 'score12', 'score2', 'score22', 'score6']
['name1', 'name10', 'name12', 'name2', 'name22', 'name6']
['email1', 'email10', 'email12', 'email2', 'email22', 'email6']

Because the sort is lexicographical, score10 and score12 appear directly after score1. The get_inv_perm function assumes the items list is unique. The remaining lists need not be.

Python, 172 bytes. Assumes names and emails are unique. Not particularly efficient as you have to do a lookup for each comparison.
NamesSorted=sorted(Names,lambda l,r:cmp(Score[Names.index(l)],Score[Names.index(r)]))
EmailSorted=sorted(email,lambda l,r:cmp(Score[email.index(l)],Score[email.index(r)]))

Ruby 108 bytes
[names, email, score].map do |z|
  z.sort! {|x, y| x.scan(/\d/).join.to_i <=> y.scan(/\d/).join.to_i }
end
puts "#{names}\n#{email}\n#{score}"

C++ 117 bytes
#define S(a)a##Sorted.push_back(a[i])
for(auto a:ScoreSorted){int i=0;for(auto b:Score)a==b?S(Names),S(Email),0:++i;}

Notice that I am making two assumptions:

strings vectors for to represent all lists
it is OK to capitalize the name of the unsorted email list (email -> Email)

Sample usage:
#include <string>
#include <vector>
#include <iostream>

using namespace std;

int main()
{
    vector<string> Score = {"score1","score10","score6","score2","score22","score12"};
    vector<string> Names = {"name1","name10","name6","name2","name22","name12"};
    vector<string> Email = {"email1","email10","email6","email2","email22","email12"};

    vector<string> ScoreSorted = {"score1","score2","score6","score10","score12","score22"};
    vector<string> NamesSorted;
    vector<string> EmailSorted;

#define S(a)a##Sorted.push_back(a[i])
for(auto a:ScoreSorted){int i=0;for(auto b:Score)a==b?S(Names),S(Email),0:++i;}

    for (auto i : NamesSorted) {
        cout << i << endl;
    }
    for (auto i : EmailSorted) {
        cout << i << endl;
    }
}


text:
Meta regex golf
In the spirit of this xkcd

Write a program that plays regex golf with arbitrary pairs of lists. The program should at least attempt to make the regex short, a program that just outputs /^(item1|item2|item3|item4)$/ or similar is not allowed.
Scoring is based on the ability to generate the shortest regex. The test lists are those of successful and unsuccessful US presidential candidates, found here (thanks @Peter). Of course, the program must work for all disjoint lists, so simply returning an answer for the president one doesn't count.

/^item1|atem2|item3|item4$/ probably has unintended precedence (string has to either begin with item1, contain atem2, contain item3, or end with item4).

This would be a more interesting challenge if it had a scoring system based primarily on the size of the regexes generated.

@PeterTaylor Have any example lists?

In the spirit of the XKCD title text, successful and unsuccessful US presidential candidates. (NB I made this list by hand following Wikipedia, so there might be small errors; I've removed from the list of losers all surnames matching a winner, because otherwise distinguishing the lists is impossible, but I've deliberately not otherwise deduplicated).

I wonder if Randall Munroe is a better writer of code-golf challenges than we are...

I wonder if Randall Munroe is gonna throw down on this question.

Yay, a list of answers to run the program from panel 2 and produce the grep-regex for panel 3!

Perl (111 110 122 characters)
use Regexp::Assemble;@ARGV=shift;my$r=new Regexp::Assemble;chomp,add$r "^\Q$_\E\$"while<>;$_=as_string$r;s/\(\?:/(/g;print

This uses CPAN module called Regexp::Assemble in order to optimize the regular expressions. Because what is the better language for regular expressions then Perl.
Also, readable version, just for fun (made with help of -MO=Deparse).
use Regexp::Assemble;
my $r = Regexp::Assemble->new;
while (<>) {
    chomp($_);
    $r->add("^\Q$_\E\$");
}
$_ = $r->as_string;
# Replace wasteful (?:, even if it's technically correct.
s/\(\?:/(/g;
print $_;

Sample output (I did CTRL-D after item4).
$ perl assemble.pl
item1
atem2
item3
item4
^(item[134]|atem2)$

Also, as a bonus, I'm writing the regex for every word in the question.
^(a((ttemp)?t|llowed\.|rbitrary)?|\/\^item1\|atem2\|item3\|item4\$\/|s(ho(rt,|uld)|imilar)|p((air|lay)s|rogram)|(Writ|mak|Th)e|l(ists\.|east)|o([fr]|utputs)|t(h(at|e)|o)|(jus|no)t|regex|golf|with|is)$

Also, list of presidents (262 bytes).
^(((J(effer|ack|ohn)s|W(ashingt|ils)|Nix)o|Van Bure|Lincol)n|C(l(eveland|inton)|oolidge|arter)|H(a(r(rison|ding)|yes)|oover)|M(cKinley|adison|onroe)|T(a(ylor|ft)|ruman)|R(oosevelt|eagan)|G(arfield|rant)|Bu(chanan|sh)|P(ierce|olk)|Eisenhower|Kennedy|Adams|Obama)$

This appears to read stdin for one list and force the other to be empty. Surely that's not what the question is asking for?

@PeterTaylor: Well, it's not that the second list is of any importance. Unless second list has duplicates of first list, the regexp is valid. It would be nice to have a shorter regexp, but I'm sort of lazy.

IMO you should at least have a way to take it as input, even if you then discard it.

@PeterTaylor: If you say so. My program now takes two arguments, one of them being the first list.

This is nice! The question has changed slightly, could you run it on the given list pair and count the characters in the result?

@Manishearth: Done.

This is cool; but it produces needlessly long expressions since it creates exclusion (for any other list) by matching every possible full word.  Which is not quite the same spirit as the original golf.

Not my solution (obviously I'm not peter norvig!) but here's a solution of the (slightly modified) question courtesy of him:
http://nbviewer.ipython.org/url/norvig.com/ipython/xkcd1313.ipynb
the program he gives is as follows (his work, not mine):
def findregex(winners, losers):
    "Find a regex that matches all winners but no losers (sets of strings)."
    # Make a pool of candidate components, then pick from them to cover winners.
    # On each iteration, add the best component to 'cover'; finally disjoin them together.
    pool = candidate_components(winners, losers)
    cover = []
    while winners:
        best = max(pool, key=lambda c: 3*len(matches(c, winners)) - len(c))
        cover.append(best)
        pool.remove(best)
        winners = winners - matches(best, winners)
    return '|'.join(cover)

def candidate_components(winners, losers):
    "Return components, c, that match at least one winner, w, but no loser."
    parts = set(mappend(dotify, mappend(subparts, winners)))
    wholes = {'^'+winner+'$' for winner in winners}
    return wholes | {p for p in parts if not matches(p, losers)}

def mappend(function, *sequences):
    """Map the function over the arguments.  Each result should be a sequence.
    Append all the results together into one big list."""
    results = map(function, *sequences)
    return [item for result in results for item in result]

def subparts(word):
    "Return a set of subparts of word, consecutive characters up to length 4, plus the whole word."
    return set(word[i:i+n] for i in range(len(word)) for n in (1, 2, 3, 4))

def dotify(part):
    "Return all ways to replace a subset of chars in part with '.'."
    if part == '':
        return {''}
    else:
        return {c+rest for rest in dotify(part[1:]) for c in ('.', part[0]) }

def matches(regex, strings):
    "Return a set of all the strings that are matched by regex."
    return {s for s in strings if re.search(regex, s)}

answer = findregex(winners, losers)
answer
# 'a.a|i..n|j|li|a.t|a..i|bu|oo|n.e|ay.|tr|rc|po|ls|oe|e.a'

where winners and losers are the winners and losers lists respectively (or any 2 lists of course) see the article for detailed explanations.

While the linked article is interesting and I enjoyed reading it, this would have been better posted as a comment on the question instead of as an answer since it doesn't answer the posed question.

You're right, it might have been better as a comment, I posted it as an answer simply because it answers the question perfectly. I didn't copy out the solution as I thought that'd be disingenuous and trying to take credit for someone elses work, in addition to providing a program that plays regex golf with 2 pairs of lists it also gives a fitness function and detailed code explanation along with the parallel to the set cover problem which I hadn't considered. If you still think it's not relevant, let me know, I'll delete and post as a comment.

If you're worried about taking credit for someone else's work, flag and ask for a mod to make your answer "Community wiki".

@PeterTaylor cool, I didn't know that was the protocol, done.

My solution written in Factor:
USING:
    formatting fry
    grouping
    kernel
    math math.combinatorics math.ranges
    pcre
    sequences sets ;
IN: xkcd1313

: name-set ( str -- set )
    "\\s" split members ;

: winners ( -- set )
    "washington adams jefferson jefferson madison madison monroe
monroe adams jackson jackson vanburen harrison polk taylor pierce buchanan
lincoln lincoln grant grant hayes garfield cleveland harrison cleveland     mckinley
 mckinley roosevelt taft wilson wilson harding coolidge hoover roosevelt
roosevelt roosevelt roosevelt truman eisenhower eisenhower kennedy johnson     nixon
nixon carter reagan reagan bush clinton clinton bush bush obama obama" name-set ;

: losers ( -- set )
    "clinton jefferson adams pinckney pinckney clinton king adams
jackson adams clay vanburen vanburen clay cass scott fremont breckinridge
mcclellan seymour greeley tilden hancock blaine cleveland harrison bryan bryan
parker bryan roosevelt hughes cox davis smith hoover landon wilkie dewey dewey
stevenson stevenson nixon goldwater humphrey mcgovern ford carter mondale
dukakis bush dole gore kerry mccain romney" name-set winners diff
    { "fremont" } diff "fillmore" suffix ;

: matches ( seq regex -- seq' )
    '[ _ findall empty? not ] filter ;

: mconcat ( seq quot -- set )
    map concat members ; inline

: dotify ( str -- seq )
    { t f } over length selections [ [ CHAR: . rot ? ] "" 2map-as ] with map ;

: subparts ( str -- seq )
    1 4 [a,b] [ clump ] with mconcat ;

: candidate-components ( winners losers -- seq )
    [
        [ [ "^%s$" sprintf ] map ]
        [ [ subparts ] mconcat [ dotify ] mconcat ] bi append
    ] dip swap [ matches empty? ] with filter ;

: find-cover ( winners candidates -- cover )
    swap [ drop { } ] [
        2dup '[ _ over matches length 3 * swap length - ] supremum-by [
            [ dupd matches diff ] [ rot remove ] bi find-cover
        ] keep prefix
    ] if-empty ;

: find-regex ( winners losers -- regex )
    dupd candidate-components find-cover "|" join ;

: verify ( winners losers regex -- ? )
    swap over [
        dupd matches diff "Error: should match but did not: %s\n"
    ] [
        matches "Error: should not match but did: %s\n"
    ] 2bi* [
        dupd '[ ", " join _ printf ] unless-empty empty?
    ] 2bi@ and ;

: print-stats ( legend winners regex -- )
    dup length rot "|" join length over /
    "separating %s: '%s' (%d chars %.1f ratio)\n" printf ;

: (find-both) ( winners losers legend -- )
    -rot 2dup find-regex [ verify t assert= ] 3keep nip print-stats ;

: find-both ( winners losers -- )
    [ "1 from 2" (find-both) ] [ swap "2 from 1" (find-both) ] 2bi ;

IN: scratchpad winners losers find-both
separating 1 from 2: 'a.a|a..i|j|li|a.t|i..n|bu|oo|ay.|n.e|ma|oe|po|rc|ls|l.v' (55 chars 4.8 ratio)
separating 2 from 1: 'go|e..y|br|cc|hu|do|k.e|.mo|o.d|s..t|ss|ti|oc|bl|pa|ox|av|st|du|om|cla|k..g' (75 chars 3.3 ratio)

It's the same algorithm as Norvig's. If hurting readability is the goal then you can probably golf away many more characters.

FYI, you are missing a bunch of the losers from the official list (Burr, Jay, Badnarik, probably others I'm not seeing). So, your results are incorrect; for example, the first regex doesn't work, because it matches Burr and Jay.

My code is not in a very golf-ish and condensed fashion, but you can check it at https://github.com/amitayd/regexp-golf-coffeescript/ (or specifically the algorithm at src/regexpGolf.coffee).
It's based on Peter Norvig's algorithm, with two improvements:

Create parts to use with character sets (i.e. use [ab]z, [ac]z, and [bc]z if valid parts are az, bz and cz).
Allow to construct "top optimal paths" of covers, and not just a cover made of the best candidate at each iteration.

(And also threw in an optional randomness)
For the sets of winners/losers in this quiz I found a 76 chars regex using it:
[Jisn]e..|[dcih]..o|[AaG].a|[sro].i|T[ar]|[PHx]o|V|[oy]e|lev|sh$|u.e|rte|nle

Some more details in my blog post about porting the solver to coffeescript.

Could you please contain your code in your answer? Otherwise, we can't see the code without clicking on the link!