text:
The Luhn algorithm for verifying credit card numbers, etc
Challenge
Write the shortest program or function to calculate the Luhn Algorithm for verifying (credit card) numbers.
Luhn algorithm explained
From RosettaCode, this algorithm for the purposes of this challenge is specified as such, with the example input of 49927398716:
Reverse the digits, make an array:
    6, 1, 7, 8, 9, 3, 7, 2, 9, 9, 4
Double the numbers in odd indexes:
    6, 2, 7, 16, 9, 6, 7, 4, 9, 18, 4
Sum the digits in each number:
    6, 2, 7, 7, 9, 6, 7, 4, 9, 9, 4
Sum all of the numbers:
    6 + 2 + 7 + 7 + 9 + 6 + 7 + 4 + 9 + 9 + 4 = 70
If the sum modulo 10 is 0, then the number is valid:
    70 % 10 = 0 => valid

IO Rules
Input: A string or number (your choice), in your language's input/output format of choice
Output: A truthy or falsy value, respectively, indicating whether or not the input is valid according to the test above.
Notes / Tips

Try not to accidentally post your own credit card or account numbers, if you use them to test :)
If the input is invalid and impossible to process with the specified algorithm (i.e, too short to work with), you can do whatever you want, including blow up my computer.
However, the previous bullet does not mean that your language can do whatever it wants with Numbers that are too large for it to handle. If your language isn't capable of handling a test case, then consider taking a string as input.

Examples
The following examples were validated with this Python script; if you think one is wrong or have a question, just ping @cat.
49927398716      True
49927398717      False
1234567812345670 True
1234567812345678 False
79927398710      False
79927398711      False
79927398712      False
79927398713      True
79927398714      False
79927398715      False
79927398716      False
79927398717      False
79927398718      False
79927398719      False
374652346956782346957823694857692364857368475368 True
374652346956782346957823694857692364857387456834 False
8 False **
0 True  **

** according to the Python implementation, but you may do anything because these are too short to be eligible by a strict adherence to the specification.

If any of the above invalidates existing answers (though I believe that should not be possible), then those answers are stil valid. However, new answers, in order to be valid, should follow the specification above.
Leaderboard

var QUESTION_ID=22,OVERRIDE_USER=73772;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

Golfscript - 24 chars
-1%{2+0!:0)*109%+}*10%8=

Explanation:

-1% reverses the string
{ begins a block (which we use as a loop). Each character in the strings is pushed as it's ascii value.

2+ adds 2. (the ascii value of a digit is 48+n, so we have 50+n now and the last digit is n)
0!:0 inverts the value of 0 and stores it (everything is a variable), so we have 1 on the first iteration, 0 on the second, etc.
)* adds one to this value and multiplies it, so we multiply by 2, then 1, then 2, etc.
109% is remainder modulo 109. This affects only values 5-9 which have been doubled and reduces them to the correct value.
+ adds this value to the running sum

}* ends the block and does a 'fold' operation. First, the first character is pushed (since we have reversed, this is the check digit). Then, alternate pushing and executing the block. Thus, we are using the first character's ascii value as the starting value for the running sum.
10% takes the remainder modulo 10.
8= will return 1 if the value is 8. We use this because we did not normalize the first pushed character (the check digit).

One might think that we could use 8- instead of 2+ to save a character by changing 109% to 89%, except then we would need to add a space so the - is subtraction (instead of -0).

GolfScript, 44 chars
-1%{16%}%2/1,\+{(\.{0=2*.9>9*-+}{;}if+}*10%!

Selected commentary
Interestingly, the first two items below demonstrate three completely different uses of the % operator: array selection, map, and mod. Most GolfScript operators are "context-sensitive", giving them hugely divergent behaviours depending on what types the arguments are.

-1% reverses the string. This is important as the digit pairs are counted from the right.
{16%}% converts all the ASCII digits into numbers, by modding them with 16.
2/ splits the array into groups of 2.
1, is a cheap way to do [0].
\+ effectively prepends the 0 to the digits array. It does this by swapping then concatenating.

The 0 is prepended in preparation for the fold that comes in next. Rather than taking an explicit initial value, GolfScript's fold uses the first item in the array as the initial value.
Now, let's look at the actual fold function. This function takes two arguments: the folded value, and the current item on the array (which in this case will be an array of 2 or (uncommonly) 1, because of the 2/ earlier). Let's assume the arguments are 1 [2 3].

(\. splits out the leftmost array element, moves the remaining array to the front, then copies it. Stack now looks like: 1 2 [3] [3].
The if checks if the array is empty (which is the case for the last group when dealing with an odd-sized account number). If so, then no special processing happens (just pop off the empty array).
For an even group:

0= grabs the first (only, in this case) element of the array. 1 2 3
2* doubles the number. 1 2 6
.9>9*- subtracts 9 from the number if it's greater than 9. Implemented as: copy the number, compare with 9, multiply the result (which is either 0 or 1) with 9, then subtract. 1 2 6
+ finally adds that to the first number. 1 8

+ (after the if) adds the result of the if to the original value, resulting in the new folded value.

After the folding completes, we simply mod with 10 (10%), and negate the result (!), so that we return 1 iff the sum is a multiple of 10.

This seems to return 0 for the example number on wikipedia (49927398716)

nm. I forgot to use echo -n

@gnibbler: Haha, fail. :-P (Seriously, I got stung by that one too, in my initial testing.)

A few places to save a few easy characters here. -1% 2/ can be combined into -2/. 1, can be replaced with 0 (0 is coerced to an array, then + is concatenate). 9>9*- can be replaced with 9>+ (since we're only concerned with the last digit). Also, the checking for odd lengths is a bit long, using .,2%,\+ is shorter. After doing this, we can also change {16%}% and (\0= into {16}/ (inside the loop). Once you've done all that, it'll look something like this: .,2%,\+-2/0\+{{16%}/2*.9>+++}*10%!.

@Nabb: Thanks! I'll incorporate those into my solution, although it looks like you already have one that's kicking serious arse. :-)

Yep, Nabb kicked ass on this one

Python, 73 69 characters
def P(x):D=map(int,x);return sum(D+[d-d/5*9for d in D[-2::-2]])%10==0

You can save two more chars by not looping backwards : D[-2::-2] -> D[1::2] as the order of a sum isn't important :)

==0 can be shortened to <1

Python 3, 77 bytes
c=lambda a:sum(sum(divmod(int(a[-e-1])<<e%2,10))for e in range(len(a)))%10==0

C# 119 characters:
bool l(string n){return(String.Join("",n.Reverse().Select((x,i)=>(x-48)*(i%2<1?1:2)+"").ToArray()).Sum(x=>x-48))%10<1;}

Not too bad for a code golf n00b in a statically typed language, I hope.
This can be reduced to 100:
bool l(string n){return String.Join("",n.Reverse().Select((x,i)=>(x-48)*(i%2+1))).Sum(x=>x+2)%10<1;}

It's a good idea, and an interesting approach, but it doesn't appear to work. At least not with my few tests. It looks like the "i" in your first lambda is supposed to be the index of the character in the string. Does that work as it should? If so, why do you reverse the string only to then modify it based on index position? Seems a bit redundant, no?

I only tested one of my credit cards and a few off by one errors from it TBH. (Using the VS 2008 debugger) The algorithm is supposed to double every second digit starting with the LAST digit.  If I didn't reverse the string, it would be incorrect for strings with odd lengths.

Turns out I did have the result of i%2<1?1:2 backwards.  Thanks.

PHP, 108 bytes
<?function v($s,$t=0){for($i=strlen($s);$i>=0;$i--,$c=$s[$i])$t+=$c+$i%2*(($c>4)*-4+$c%5);return!($t % 10);}

Golfscript - 34 chars
{15&}%.-2%\);-2%{.+(9%)}%+{+}*10%!

Example number from wikipedia page 4992739871
{15&}%  does a bitwise and of each ascii digit with 00001111
        now I have a list of digits
        [4 9 9 2 7 3 9 8 7 1 6]
.       makes a copy of the list, now I have two identical lists
        [4 9 9 2 7 3 9 8 7 1 6] [4 9 9 2 7 3 9 8 7 1 6]
-2%     like [::-2] in python takes every second element in reverse
        [4 9 9 2 7 3 9 8 7 1 6] [6 7 9 7 9 4]
\       swap the two lists around
        [6 7 9 7 9 4] [4 9 9 2 7 3 9 8 7 1 6]
);      drop the last digit off the list
        [6 7 9 7 9 4] [4 9 9 2 7 3 9 8 7 1]
-2%     same as before
        [6 7 9 7 9 4] [1 8 3 2 9]
{       for each item in the list ...
.+      ... double it ...
(       ... subtract 1 ...
9%      ... mod 9 ...
)}%     ... add 1 ...
        [6 7 9 7 9 4] [2 7 6 4 9]
+       join the two lists
        [6 7 9 7 9 4 2 7 6 4 9]
{+}*    add the elements up
        70
10%     mod 10
        0
!       invert the result
        1

The .+(9%) is very innovative (for me, anyway). I like! +1

Srsly though, GolfScript needs a partitioning operator, so you don't need to do this "drop end item off and repeat" nonsense. :-)

@Chris, I learned about that many years ago called "casting out nines". It is a neat way to double check longhand additions and multiplications

This won't work for a value of 0 being doubled (0(9%) is 9 and not 0).

Haskell, 96 bytes
There must be a better/shorter way, but here's my Haskell solution in 96 characters:
l=(==0).(`mod`10).sum.zipWith($)(cycle[id,\x->x`mod`5*2+x`div`5]).reverse.map((+(-48)).fromEnum)

Sadly the digitToInt function can only be used if you import Data.Char first. Otherwise I could get down to 88 characters by replacing ((+(-48)).fromEnum) with  digitToInt.

Ruby - 85 characters
def f s
l=s.size
s.chars.map{|k|(i=k.to_i*((l-=1)%2+1))%10+i/10}.inject(:+)%10==0
end

You probably know about this, but you could do .sum instead of .inject(:+) to save 7 bytes

D, 144 bytes
bool f(S)(S s){int t(C)(C c){return to!int(c)-'0';}int n,v;foreach(i,c;array(retro(s))){v=i&1?t(c)*2:t(c);n+=v>=10?v%10+v/10:v;}return n%10==0;}

More legibly:
bool f(S)(S s)
{
    int t(C)(C c)
    {
        return to!int(c) - '0';
    }

    int n, v;

    foreach(i, c; array(retro(s)))
    {
        v = i & 1 ? t(c) * 2 : t(c);

        n += v >= 10 ? v % 10 + v / 10 : v;
    }

    return n % 10 == 0;
}

Windows PowerShell, 82
filter f{!((''+($_[($_.length)..0]|%{+"$_"*($i++%2+1)})-replace'.','+$&'|iex)%10)}

History:

2011-02-13 03:08 (84) First attempt.
2011-02-13 12:13 (82) I don't need to join, as spaces do not hurt. +1 + +3 can still be evaluated.

Jelly, 12 11 9 bytes
ṚḤÐeDFS⁵ḍ

Try it online!
How it works
ṚḤÐeDFS⁵ḍ - Main link. Takes an integer n on the left
Ṛ         - Cast n to digits and reverse
  Ðe      - To values at even indices:
 Ḥ        -   Unhalve; Double
    D     - Cast to digits
     F    - Flatten
      S   - Sum
        ḍ - Divisible by:
       ⁵  - 10?

PowerShell 123
filter L($x){$l=$x.Length-1;$l..0|%{$d=$x[$_]-48;if($_%2-eq$l%2){$s+=$d}elseif($d-le4){$s+=$d*2}else{$s+=$d*2-9}};!($s%10)}

Q, 63
{0=mod[(+/)"I"$(,/)($)($)@["I"$'x;1+2*'(!)(_)((#)x)%2;*;2];10]}

usage
q){0=mod[(+/)"I"$(,/)($)($)@["I"$'x;1+2*'(!)(_)((#)x)%2;*;2];10]}"79927398711"
0b
q){0=mod[(+/)"I"$(,/)($)($)@["I"$'x;1+2*'(!)(_)((#)x)%2;*;2];10]}"79927398712"
0b
q){0=mod[(+/)"I"$(,/)($)($)@["I"$'x;1+2*'(!)(_)((#)x)%2;*;2];10]}"79927398713"
1b

47 bytes with {0=mod[sum"J"$raze($)($)x*#:[x]#1 2]10}"I"$'(|) a different way to double the odd indices.

APL, 28 bytes
{0=10|+/⍎¨∊⍕¨v×⌽2-2|⍳⍴v←⍎¨⍵}

Exploded view
{                     v←⍎¨⍵}  ⍝ turn the string into a numeric vector of its digits, v
                2-2|⍳⍴v       ⍝ make a vector of the same length, with 2 in every 2nd place
             v×⌽              ⍝ multiply it with v, starting from the right
          ∊⍕¨                 ⍝ turn each component into a string and collect all the digits
      +/⍎¨                    ⍝ turn each digit again into a number and sum them
 0=10|                        ⍝ check whether the sum is a multiple of 10

Examples
      {0=10|+/⍎¨∊⍕¨v×⌽2-2|⍳⍴v←⍎¨⍵} '79927398713'
1
      {0=10|+/⍎¨∊⍕¨v×⌽2-2|⍳⍴v←⍎¨⍵} '123456789'
0

-2: {0=10|+/⍎¨∊⍕¨⍵×⌽2-2|⍳⍴⍵}⍎¨

x86-16 machine code, 27 bytes
Binary:
00000000: bb00 0103 f1fd ac2c 30f6 df78 06d0 e0d4  .......,0..x....
00000010: 0a02 dc02 d8e2 ef93 d40a c3              ...........

Listing:
BB 0100         MOV  BX, 100H           ; running sum (BL) to 0, BH to a positive value
03 F1           ADD  SI, CX             ; start at end of input string
FD              STD                     ; set LODSB direction to decrement
            DIGIT_LOOP:
AC              LODSB                   ; load next digit into AL, decrement SI
2C 30           SUB  AL, '0'            ; convert ASCII char to binary value
F6 DF           NEG  BH                 ; flip sign of BH to alternate odd/even index
78 06           JS   IS_EVEN            ; if not odd index, do not double
D0 E0           SHL  AL, 1              ; double the value
D4 0A           AAM                     ; split digits (ex: 18 --> AH = 1, AL = 8)
02 DC           ADD  BL, AH             ; add tens digit to running sum
            IS_EVEN:
02 D8           ADD  BL, AL             ; add ones digit to running sum
E2 EF           LOOP DIGIT_LOOP
93              XCHG AX, BX             ; sum is in BL, move to AL for mod 10 check
D4 0A           AAM                     ; ZF = ( AL % 10 == 0 )
C3              RET                     ; return to caller

Uses (abuses) x86's BCD-to-binary instruction AAM to handle the individual digit splitting and modulo 10 check.
Callable function, input card num string pointer in SI, length in CX.  Output: ZF if valid.
Example test program output:

Alternate version, 29 bytes
33 DB           XOR  BX, BX             ; running sum (BL) to 0
03 F1           ADD  SI, CX             ; start at end of string
4E              DEC  SI                 ; align for WORD
FD              STD                     ; set LODSB direction to decrement
            DIGIT_LOOP:
AD              LODSW                   ; load next two digits into AH:AL, dec SI by 2
25 0F0F         AND  AX, 0F0FH          ; convert ASCII chars to binary value
02 DC           ADD  BL, AH             ; add ones digit of even index to sum
49              DEC  CX                 ; decrement counter for WORD
74 0A           JZ   DONE               ; if input is odd length, will be 0 at the end
D0 E0           SHL  AL, 1              ; double the value
D4 0A           AAM                     ; split digits (ex: 18 --> AH = 1, AL = 8)
02 DC           ADD  BL, AH             ; add tens digit to sum
02 D8           ADD  BL, AL             ; add ones digit to sum
E2 ED           LOOP DIGIT_LOOP
            DONE:
93              XCHG AX, BX             ; move sum to AL for mod 10 check
D4 0A           AAM                     ; ZF = ( AL % 10 == 0 )
C3              RET                     ; return to caller

This version loads two digits at the same time, eliminating the flip/flop branch.  The issue here is having to check for an odd number of digits on the input and discard the value in memory right before the beginning of the string once it reaches the last word.  Obviously not shorter, but perhaps someone clever can golf it more!

I haven't spent very long staring at this, but... Why do you need to iterate through the string backwards? If you iterated forwards, it seems like you'd get the same result, but be able to shave off those initial 3 bytes (setting SI and the direction flag [which you can assume is always clear]).

@CodyGray IIRC I think it has to do with having an odd number of digits, and the LUHN algorithm expecting you to operate on the last digits first. Maybe I should take another look though...

Yeah, I realize it's an old answer. The Luhn algorithm was brought up in a chat room earlier, so I was considering it, dreaming of it in x86 asm. I decided to check Code Golf, and sure enough, it was already here. With a pretty solid-looking x86 asm answer. Thus, I immediately set out to nitpick. ;-) We were specifically discussing whether it is necessary to iterate backwards. The reference implementation in pseudocode on Wikipedia doesn't appear to go backwards. Didn't even notice about the missing ret though. Would take some effort to clean up, probably more than it's worth.

@CodyGray my quick reading of the Wiki implementation, it seems to first determine if the number of digits is odd or even (parity := nDigits modulus 2) and then checks every time through the loop if that index corresponds to a relative odd or even index (if i modulus 2 = parity). Maybe that could be golfed, though I tend to think the 3 bytes to start from the end isn't too bad. Also, it looks like I'm going to have to take a +4 bytes penalty to get this submission up to spec with the rules. I guess I didn't quite understand them when I wrote this one. :)

@CodyGray I played with the idea of iterating forwards using the Wiki-inspired if ( originalCx & 1 == currentCx & 1 ) then..., but got a bit fiddly in ASM and was longer for me. Then I tried loading two bytes at a time (while still going backwards) and got it down to +2 bytes longer than the original. Posted it anyway in case it inspires another idea. Would love to see the answer you "dreamed" up too! :)

You'd probably also like to read the novels that I dream up while sleeping, too. I'll let you know. :-p In your second submission, could the 3-byte dec cx + jz done be replaced with a 2-byte loopz done?

@CodyGray so I don't think it's going to be a drop-in change... loopz is an AND condition - branch if cx non-zero and zf is 1. So in other words would still need to set zf somewhere first. Though, it's an interesting idea to see if it can be refactored to set that flag another way in an operation already being done. Will have to try that later on!

Oh, right, duh. You just want loop, not loopz. I was for some reason thinking that dec didn't set zf, but it's actually cf that it doesn't set.

Perl, 46 42 41 bytes
Includes +1 for -p
Give input on STDIN:
luhn.pl <<< 79927398713

luhn.pl:
#!/usr/bin/perl -p
s%.%$=-=-$&-$&*1.2*/\G(..)+$/%eg;$_=/0$/

Can you please explain how this works? You seem to be decrementing by the match and then also by the match times 1.2 but only in the correct positions. Why 1.2? Shouldn't it be $=-=-$&-$&*/\G(..)+$/?

@msh210: It encodes the effect of the multiplication by 2. 0..4 * 2 gives 0, 2, 4, 6, 8 but 5..9 gives 10,12,14,16,18 which sum to 1 3 5 7 9 which have the same last digits as 11 13 15 17 19 which are the same values as 0..9 * 2.2 if you truncate to integer. The first $& already contributes a factor 1, so a correction by 1.2 is still needed. $= can only hold integers and starts with a value that ends on 0 so takes care of the truncating. The negative values are needed since the /\G/ regex changes any $& still on the evaluation stack so they need to be changed

Oh. Brilliant! And thanks for the explanation.

05AB1E, 12 10 bytes
RSāÈ>*SOTÖ

Try it online!
or as a Test Suite
Explanation
R             # reverse input
 S            # split to list of digits
  ā           # push range[1 ... len(input)]
   È          # map isEven on each
    >         # increment
     *        # multiply doubling every other item
      SO      # sum digits
        TÖ    # mod 10 == 0

C (clang), 264 212 196 175 172 bytes
l,x;main(i){char*s;gets(s);int n[i=l=strlen(s)];for(;i--;)n[i]=s[i]-48;for(;(i+=2)<l;n[i]>9?n[i]=n[i]/10+n[i]%10:0)n[i]*=2;for(;l--;)x+=n[l];printf(x%10<1?"True":"False");}

Try it online!
Simply the basic way of programming the algorithm, but all whitespace is removed. All I could say is that there are a bunch of for-loops in this one.
Thanks to ceilingcat for golfing 52 bytes, another 16 bytes, and another 21 bytes, and another 3 bytes.

156 bytes

JavaScript 1.8: 106 characters
This is an original solution I came up with before I found this post:
function(n){return!(n.split('').reverse().reduce(function(p,c,i){return(+c&&((c*(1+i%2)%9)||9))+p},0)%10)}

Readable form:
function luhnCheck(ccNum) {
    return !(                                  // True if the result is zero.
             ccNum.split('').
               reverse().                      // Iterate over the string from rtl.
               reduce(function(prev, cur, idx) {
                 return prev +                 // Sum the results of each character.
                        (+cur &&               // If the current digit is 0, move on.
                         ((cur * (1 + idx % 2) // Double cur at even indices.
                           % 9) || 9));        // Sum the digits of the result.
               }, 0)
            % 10);                             // Is the sum evenly divisible by 10?
}

JavaScript (ES6), 61 bytes
Sum of digits of 2*n is 2*n if n in 0..4, 2*n-9 if n in 5..9. That said, all the sum can be computed in one step.
s=>!([...s].reduceRight((t,d)=>t-d-i++%2*(d>4?d-9:d),i=0)%10)

Powershell, 74 bytes
param($s)$s[$s.Length..0]|%{(1+$i++%2)*"$_"}|%{$r+=$_-9*($_-gt9)}
!($r%10)

Explanation

for each char of an argument string, in reverse order
get a digit of double value of a digit
a double value of a digit can not be greater then 18. Therefore, we accumulate a value minus 9 if value > 9
return true if the remainder of the division by 10 is 0

Test script
$f = {

param($s)$s[$s.Length..0]|%{(1+$i++%2)*"$_"}|%{$r+=$_-9*($_-gt9)}
!($r%10)

}

@(
    ,("49927398716"      , $True)
    ,("49927398717"      , $False)
    ,("1234567812345670" , $True)
    ,("1234567812345678" , $False)
    ,("79927398710"      , $False)
    ,("79927398711"      , $False)
    ,("79927398712"      , $False)
    ,("79927398713"      , $True)
    ,("79927398714"      , $False)
    ,("79927398715"      , $False)
    ,("79927398716"      , $False)
    ,("79927398717"      , $False)
    ,("79927398718"      , $False)
    ,("79927398719"      , $False)
    ,("374652346956782346957823694857692364857368475368" , $True)
    ,("374652346956782346957823694857692364857387456834" , $False)
    ,("8" , $False)
    ,("0" , $True)
) | % {
    $s, $expected = $_
    $result = &$f $s
    "$($result-eq$expected): $result : $s"
}

Output
True: True : 49927398716
True: False : 49927398717
True: True : 1234567812345670
True: False : 1234567812345678
True: False : 79927398710
True: False : 79927398711
True: False : 79927398712
True: True : 79927398713
True: False : 79927398714
True: False : 79927398715
True: False : 79927398716
True: False : 79927398717
True: False : 79927398718
True: False : 79927398719
True: True : 374652346956782346957823694857692364857368475368
True: False : 374652346956782346957823694857692364857387456834
True: False : 8
True: True : 0

K (ngn/k), 26 bytes
{~10!+//10\(1+2!!#x)*.'|x}

Try it online!
Another k variant, with a major debt to @streetster's answer.

1+2!!#x -> 1+=\~x

i rolled back the above change because =\ works differently now

GolfScript, 31 bytes
.,2%0\@{48-..4>+@!:a*++a}/;10%!

Try it online!
Golfscript pushes the input as a list of characters to the stack
at the start of the program.
.                                Duplicate the top of the stack (input)
 ,2%                             Compute the modulo 2 of the length of the input,
                                 pushed 1/0 on the stack if the number if odd/even
    0                            Push an accumulater var on the stack, set to 0

     \                           Flip the even/odd and accumulator order on the stack
      @                          Bring the 3rd entry forward, input to the top

       {                }        Code block...
                         /       Apply the block of code to the elements of the list at
                                 the top of the stack. Each time through the loop, the
                                 next element from the list if pushed to the top of the
                                 stack
        48-                      Subtract "0" from the top of stack (which is a codepoint
                                 for the current digit/character)
           ..                    Duplicate the top of stack (the current digit) twice
             4>+                 If the current digit is >4 add one to the digit
                @                Pull the 3rd entry, the even/odd indicator, to the top
                 !:a             Flip the value and save in variable "a"
                    *            Multiple the top two stack entries, will be "0" or the
                                 value of current digit, with or without "1" more for the
                                 "+10" rule
                     ++          Add the current digit, to the possible "double" and
                                 "even/odd" bump
                       a         Push the flipped even/odd indicated to the top
                          ;      Drop the stop of stack, the even/odd indicator
                           10%   Find the modulo 10 of the accumulated digits
                              !  Invert the result

The only thing on the stack is the answer, which is printed by default

Factor + validators, 5 bytes
luhn?

Try it online!

Scala: 132
def q(x:Int)=x%10+x/10
def c(i:String)={val s=i.reverse
(s(0)-48)==10-(s.tail.sliding(2,2).map(n=>(q((n(0)-48)*2)+n(1)-48)).sum%10)}

invocation:
c("79927398713")

reverse ("79927398713") = 31789372997
s(0), s.tail: (3)(1789372997)
sliding (2,2) = (17 89 37 29 97)
map (q((n(0)-48*2 + n(1)-48)) => q(('1'-'0')*2)+ '7'-'0')=1*2+7

Haskell: 97
For some reason this isn't working for me, so here is my version
l=(\x->(==0)$(`mod`10).sum$zipWith($)(cycle[id,sum.map(read.(:"")).show.(*2)])(map(read.(:""))x))

K4, 35 bytes
{~.*|$+/.:',/$x*1+1{y;~x}\|x:|.:'x}

APL, 38 bytes
d←10∘⊥⍣¯1⋄{0=10|+/+/d x×1+~2|⍳⍴x←⌽d ⍵}

expects the number as a number, not a string, but that's only because tryAPL (understandably) doesn't implement ⍎
further reducible, i'm sure…

Retina, 43 42 bytes
Retina is (much) newer than this challenge.

;
r`(.);.
$1$&
\d
$*
1+
$.&
.
$*
$
$._
0$
The leading empty line is significant.
Prints 0 for falsy and 1 for truthy results.
Try it online! (Slightly modified to run all test cases at once.)
Explanation

;
Insert ; in every position to separate digits.
r`(.);.
$1$&

From the right, we repeatedly match two digits and double the left one. This way we avoid an expensive reversing of the list.
\d
$*

We match each digit and convert it to that many 1s (that is, we convert each digit to unary).
1+
$.&

This matches each unary number and converts it back to decimal by replacing it with its length. Together with the previous stage, this adds the doubled digits.
.
$*

Again, we match every character and turn it into that many 1s. That is we convert each digit individually back to unary. This also matches the ; separators, which are treated as zeros in the conversion, which means they're simply removed. Since all the unary numbers are now squashed together we've automatically added the unary representations of the all digits together.
$
$._

At the end, we insert the length of the entire string, i.e. the decimal representation of the unary checksum.
0$

Finally we count the number of matches of this regex, i.e. we check whether the decimal representation ends in 0, printing 0 or 1 accordingly.

Jelly, 14 bytes
DUḤJḤ$¦DS$€S⁵ḍ

Try it online!
Explanation:
D              get digits
 U             reverse array
   JḤ$         for every other index,
  Ḥ   ¦        double the value
          €    for each value,
       D $     get the digits
        S$     and sum them
           S   sum the list
            ⁵ḍ check if it's divisible by 10

Why is this non-competing?

@mudkip201 Correct me if I'm wrong, but this version of Jelly didn't exist when the question was asked, so it isn't valid for the question.

Pretty sure there was a meta consensus that said that languages that were made after the challenge aren't 'non-competing' any more

Japt, 14 13 bytes
Takes input as an array of digits.
ÔxÈ*ÒYu)ìxÃvA

Try it
ÔxÈ*ÒYu)ìxÃvA     :Implicit input of array
Ô                 :Reverse
 x                :Reduce by addition
  È               :After passing each element at 0-based index Y through the following function
   *              :   Multiply by
    Ò             :     Bitwise increment
     Yu           :     Y modulo 2
       )          :   End multiplication
        ì         :   Convert to digit array
         x        :   Reduce by addition
          Ã       :End function
           v      :Test for divisibility by
            A     :  10

This doesn't reverse the array, so inputs like 24 return the wrong result

Thanks, @EmbodimentofIgnorance, looks like I made a faulty assumption somewhere along the way. Fixed and saved a byte in the process.

Pxem, 0 bytes (content) + 147 bytes (filename).

Filename (escaped): .w0.-.i.c\001.+.a\001.+.t.v.m.vQJ.z.v.m.v.c.m.+.c.t.-.m.v.t.v.m.-.m\001.+.!.c\011.x\011.-XX.a.t.v.s.m.v\001.-.t.v.m.v.c0.a\046.-.v.s@.w.t.c.c.Z.m\012.%.w.d.aY.o.d.A.m.+@.a
Content is empty.

Try it online!
Usage
A single line that matches ^[0-9]+$, ending with EOF, is given from stdin. A single Y is output if and only if truthy.
Algorithm

Let l1 be a list storing each digit in reverse order.
Let s be 0.
Let l2 be an empty list.
If l1 is empty, go to step 9.
Pop one value from l1 and let it be n. Push n*(s+1) onto l2.
If last value on l2 is more than 9, subtract 9 from it.
Let s be 1-s.
Go to step 4.
Calculate (sum of each item in l2)%10.
If step 9 resulted in 0, the program returns truthy; otherwise falsey.

With comments
# getchar() unil EOF
# substract 48 for each character
.w0.-.i.c\001.+.aXX.z
# at this point stack is -1, [0-9], ..., [0-9], 48.
# add 1 to -1 so: 0, ..., 48.
# move 0 to bottom: [0-9], ..., 48, 0.
.a\001.+.t.v.m.vXX.z
# loop
# every time loop begins, bottom should be [01].
# also heap should be same as bottom.
.aQJ.zXX.z
  # to: [0-9], [01], ..., 48, ..., [01]... I think
  # WTF did I do here?
  .a.v.m.v.c.m.+.c.t.-.m.v.t.v.m.-.mXX.z
  # multiply [0-9] to ([01]+1)
  .a\001.+.!XX.z
  # subtract 9 if more than 9
  .a.c\011.x\011.-XX.aXX.z
  # move top to bottom, replacing it
  .a.t.v.s.m.vXX.z
  # alt for [01] xor 1; subtract from 1
  # then move to bottom
  .a\001.-.t.v.m.vXX.z
# break if top equals 48
.a.c0.aXX.z
# make 48 to 10, then remove botton [01]
# OBTW reversed, but whatever
.a\046.-.v.sXX.z
# loop
.a@.wXX.z
  # if size is 1; then
  .a.t.c.c.ZXX.z
    # modulo by 10
    .a.m\012.%XX.z
    # if it is 0; then print Y and exit; else exit; fi
    .a.w.d.aY.o.d.AXX.z
  # fi; push (pop+pop)
  .a.m.+
# end of loop
.a@.a

Vyxal, 12 11 bytes
-1 byte thanks to @lyxal reminding me about multibyte lambdas.
ṘÞTf‡d∑ẇ∑₀Ḋ

Try it Online!
Explanation:
             # Implicit input
Ṙ            # Reverse
 ÞT          # Transpose
   f         # Flatten list
    ‡  ẇ     # For every second element:
     d       #   Double
      ∑      #   Sum digits
        ∑    # Sum all elements
         ₀Ḋ  # x % 10 == 0?
             # Implicit output

use a multi byte lambda for 11 bytes

@lyxal Wow. I can't believe I forgot those existed. Thanks!

Julia 1.0, 51 50 bytes
~=digits;!n=(k=~n;k[2:2:end]*=2;sum(sum,.~k)%10<1)

Try it online!

GNU sed, 140 bytes
(including +1 for the -r flag)
s/^(..)*.$/0&/
s/(.)./\1x&/g
s/x[5-9]/1&/g
s/[0x]//g
s/[789]/&6/g
s/[456]/&3/g
s/[369]/&11/g
s/[258]/&1/g
s/.{10}//g
s/.+/false/
s/^$/true/

Sed is almost never the most natural language for arithmetic, but here we go:
#!/bin/sed -rf

# zero-pad to even length
s/^(..)*.$/0&/
# double every other digit
s/(.)./\1x&/g
# add carry (converts mod-9 to mod-10)
s/x[5-9]/1&/g
# convert sum to unary
s/[0x]//g
s/[789]/&6/g
s/[456]/&3/g
s/[369]/&11/g
s/[258]/&1/g
# remove whole tens
s/.{10}//g
# output 'true' or false
s/.+/false/
s/^$/true/

PHP - 136 characters
function t($c){foreach($a=str_split(strrev($c)) as $k=>&$v){$v=array_sum(str_split(($k % 2)!==0?2*$v:$v));}return !(array_sum($a)% 10);}

MATL, 23 20 bytes (non competing)
P!Utn:2X\!*t9>+s10\~

Try it online!
Outputs 1 for a valid number, 0 otherwise.
Saved three bytes thanks to Luis Mendo's suggestions.
Explanation
P       % flip the order of elements
!       % transpose into column vector
U       % convert char matrix to numeric
t       % duplicate the vector
n       % find the length
:       % create a new vector length n (1, 2, 3, ... n)
2       % number literal
X\      % take it mod 2, to make the new vector (1, 2, 1, ..., (n-1) mod 2 +1)
!       % transpose
*       % element-wise product
t       % duplicate
9       % push 9
>       % 1 if it is greater than 9
+       % add the vectors, this makes the last digit of each the same as the sum of the digits
s       % add them
10      % number literal
\       % mod 10
~       % logical 'not' (element-wise)
        % (implicit) convert to string and display

Pyt, 20 bytes
ĐḶ⌊⁺⇹ą↔⇹ř⁻2%⁺*ŚƩ1ᴇ%¬

Explanation:
                        Implicit input
Đ                       Duplicate input
 Ḷ⌊⁺                    Get length of integer in base-10 (floor(log_10(input))+1)
    ⇹                   Swap top two on stack
     ą↔                 Convert input to an array of digits, and reverse
       ⇹                Swap top two on stack
        ř⁻              Push [0,1,2,...,floor(log_10(input))]
          2%            Take previous array element-wise mod 2
            ⁺           Increment each element of the array
             *          Elementwise multiplication of the arrays
              Ś         Elementwise sum of digits
               Ʃ        Sum up array
                1ᴇ%     Mod 10
                   ¬    Negate (this returns false if not 0, and true otherwise)

Try it online!

K (oK), 28 bytes
Solution:
~10!+/48!,/$(1+2!!#x)*48!|x:

Try it online!
Examples:
~10!+/48!,/$(1+2!!#x)*48!|x:"1234567812345670"
1
~10!+/48!,/$(1+2!!#x)*48!|x:"1234567812345678"
0

Explanation:
~10!+/48!,/$(1+2!!#x)*48!|x: / the solution
                          x: / save input as variable x
                         |   / reverse it
                      48!    / mod with 48 (converts ascii -> int)
            (       )*       / multiply with stuff in brackets
                  #x         / length of x
                 !           / til, the range 0..x-1
               2!            / mod with 2 (0 1 2 3 -> 0 1 0 1)
             1+              / add 1 (0 1 0 1 -> 1 2 1 2)
           $                 / convert to string
         ,/                  / flatten string
      48!                    / convert this into integers
    +/                       / sum over the list
 10!                         / modulo 10
~                            / negate (so 1 for truthy, 0 for falsy)

Extra:
A couple of 30-byte solutions in K4, not quite as short...
~.*|$+/,/10\:'((#x)#1 2)*.:'x:
~.*|$+/.:'',/$((#x)#1 2)*.:'x:

Kotlin, 77 bytes
mapIndexed{i,c->(""+(2-(length%2 xor i%2))*(c-'0')).sumBy{it-'0'}}.sum()%10<1

Beautified
mapIndexed { i, c ->
    ("" + (2 - (length % 2 xor i % 2)) * (c - '0')).sumBy { it - '0' }
}.sum() % 10 < 1

Test
data class Test(val input: String, val output: Boolean)

val tests = listOf(
        Test("49927398716", true),
        Test("49927398717", false),
        Test("1234567812345670", true),
        Test("1234567812345678", false),
        Test("79927398710", false),
        Test("79927398711", false),
        Test("79927398712", false),
        Test("79927398713", true),
        Test("79927398714", false),
        Test("79927398715", false),
        Test("79927398716", false),
        Test("79927398717", false),
        Test("79927398718", false),
        Test("79927398719", false),
        Test("374652346956782346957823694857692364857368475368", true),
        Test("374652346956782346957823694857692364857387456834", false),
        Test("8", false),
        Test("0", true)
)

fun String.f() =
mapIndexed{i,c->(""+(2-(length%2 xor i%2))*(c-'0')).sumBy{it-'0'}}.sum()%10<1
fun main(args: Array<String>) {
    for ((input, expectedOut) in tests) {
        val actualOut = input.f()
        if (actualOut != expectedOut) {
            System.err.println("$input $expectedOut $actualOut")
        }
    }
}

TIO
TryItOnline

Dart, 120 bytes
f(s,{i=0})=>s.split('').reversed.map(int.parse).map((n)=>i++%2>0?n*2:n).map((n)=>n>9?n-10+1:n).fold(0,(p,e)=>p+e)%10==0;

Try it online!

Perl 6, 37 bytes
(*.flip.comb >>*>>[1,2]).comb.sum%%10

Try it online!
A Whatever lambda that takes a number and returns a boolean.
Explanation:
 *.flip                  # Reverse the number
       .comb             # Split to list of digits
             >>*>>       # Multiply each element by:
                  [1,2]  # The list 1,2,1,2,1,2...
(                      ).comb           # Split the list to a list of digits
                             .sum       # Get the digit sum
                                 %%10   # Return if it is divisible by 10

Julia, 67 bytes
x=digits(n)
sum(x[1:2:end])+sum(reduce(vcat,digits.(x[2:2:end]*2)))

MathGolf, 11 bytes
▒xôï¥)*Σ+♂÷

Try it online!
At least I tied with Jelly, I can't really see a way to remove a byte from this.
Explanation
▒             split to list of chars/digits
 x            reverse int/array/string
  ô           start block of length 6 (for-each)
   ï          index of current loop
    ¥         modulo 2
     )        increment
      *       pop a, b : push(a*b)
       Σ      digit sum
        +     add to the counter (implicitly calculates 0+x when stack only has one element)
              Block ends here
         ♂    push 10
          ÷   is divisible

Haskell, 73 bytes
i#0=0
i#n|m<-mod n 10=i*(m+sum[-9|m>4])+m+(1-i)#div n 10
f n=mod(0#n)10<1

Try it online!

Japt v2.0a0, 14 bytes
¬ÔxÈ*ÒYu)ìxÃvA

The first byte can be removed if I took input as array of chars.
Try it
¬                   //Split (implicit) input into list of chars
 Ô                  //Reverse
  xÈ                //Get the sum of every char after passing through the following function
    *               //  Multiply the element
     ÒYu)           //  By the index modulus 2 plus 1 (Odd -> 2, Even -> 2)
         ìx         //  And take the sum of the digits
  Ã                 //Close function
vA                  //And check if result is divisible by 10

Oh, didn't see you'd posted this before I fixed mine. Don't forget, you only have 'til Tuesday to post 3 more solutions and qualify for the additional 300 rep bounty.

APL(NARS), 37 chars, 74 bytes
{0=10∣+/{+/10 10⊤⍵}¨v+v×0=2∣⍳≢v←⌽⍎¨⍵}

test:
  f←{0=10∣+/{+/10 10⊤⍵}¨v+v×0=2∣⍳≢v←⌽⍎¨⍵}
  f '1234567812345670'
1
  f '49927398717'
0
  f '1234567812345678'
0
  f '79927398710'
0
  f '79927398719'
0
  f '374652346956782346957823694857692364857368475368'
1
  f '374652346956782346957823694857692364857387456834'
0
  f ,'8'
0
  f ,'0'
1

comment:
{0=10∣+/{+/10 10⊤⍵}¨v+v×0=2∣⍳≢v←⌽⍎¨⍵}
                                ⍎¨⍵ for each element of ⍵ (that would be char digits) convert in int
                             v←⌽    reverse the array result of above, and assign it to variable v
                           ⍳≢        produce all index of above v that are 1..≢v
                        0=2∣         produce one array of boolean where 0 means even index, 1 odd
                    v+v×            multipy that array for v itself (means get only odd ones the other 0)
                                    and sum it to v (so we have v with elements index odd duplicate)
       {+/10 10⊤⍵}¨                convert each element of the array of 2 digits base 10 than sum
   10∣+/                            sum all element mod 10
 0=                                if result is 0 return 1 (true), else return 0 (false)

PHP, 83 82 bytes
foreach(str_split(strrev($argn))as$x=>$d)$m+=$d+($d%10+$d/5|0)*$x&=1;echo!($m%10);

As standalone program, call with php -F.  Input is STDIN, output is to STDOUT as bool (1 or empty).
$ echo 49927398716|php -F luhn.php
1

$ echo 49927398717|php -F luhn.php

$ echo 1234567812345670|php -F luhn.php
1

Verify all test cases

R, 46 bytes
function(x,y=rev(x)*1:2)!sum(y%%10+y%/%10)%%10

Try it online!

Husk, 15 13 bytes
Edit: -2 bytes thanks to Razetime
¬→dṁΣzod*¢ḣ2↔

Try it online!
¬                   # logical NOT of
 →d                 # last decimal digit of
   ṁΣ               # sum of sums of results of
     z              # zipping two lists together
         ¢ḣ2        # list 1: [1,2] repeated
            ↔       # list 2: input, reversed
      o             # using these two functions:
       d*           # decimal digits of product

13 bytes using cycle

Nice!  Thanks!  Another new function used for the first time...

Zsh, 52 bytes
for j (${(Oas::)1})((s+=++i%2?j:j*2.2%10))
<<<$s[-1]

Try it Online..
Parse input into array and reverse it: ${(Oas::)1}. Then iterate over the array elements.
0 is truthy, non-zero is falsy.
From my work, the Visa test number (4111 1111 1111 1111) is embedded in my brain.
Previous efforts: 55 bytes 61 bytes 72 bytes 77 bytes

dc, 61 bytes
[A~rdZ1<S]dsSxz2%1=0[2*SaSaz1<LLaLalSx]dsLx[+z1<L]dsLxA%0=0zp

Try it online!
[A~rdZ1<S]dsSx # split: take quotient and remainder by 10, rotate quotient to top
z2%1=0 # if odd length, prepend 0 (I think. I poked it until it worked)
[2*SaSaz1<LLaLalSx]dsLx # double every other number, split them all
[+z1<L]dsLx # sum everything
A%0=0zp # if n%10 == 0, print 1; else, print 0

The last line works because:

Each register holds 0 by default
Comparisons attempt to execute whatever's in the specified register (0 here)
Executing a number simply returns the number

So if we execute the contents of register 0, then we have one item on the stack: 0. Otherwise, the stack is empty. Use z to convert this to a 0 or 1.

C (gcc), 126 110 bytes
-16 bytes thanks to ceilingcat
#define e s[1][i]
c,b;main(i,s)char**s;{for(i=strlen(s[1]);i--;b+=e-=e/10?9:0)e-=48,e*=c++%2+1;return!(b%10);}

Input is taken through an argument and output uses exit codes, 0 for false and 1 for true
Explanation:
#define e s[1][i]
c,b;
main(i,s) // i, c, and b are ints for program use
char**s; // argv, used for input
{
    for(i=strlen(s[1]); i--; b+=e-=e/10?9:0) // iterate backwards through string, and add to the total (b) while also doing the digit add
        e-=48, // subtract '0'
        e*=c++%2+1; // double each odd index
    return!(b%10); // check if b ends in 0 and return that
}

Suggest e<<=c++%2 instead of e*=c++%2+1

Vyxal, 16 bytes
₀τƛ¥₂ßd&›₀τ∑;∑₀Ḋ

Try it Online!
₀τ               # Digits...
  ƛ         ;    # Map
   ¥₂            # If register is even
     ßd          # Double
       &›        # Increment register
         ₀τ      # Digits...
           ∑     # Sum
             ∑   # Sum of all...
              ₀Ḋ # is divisible by 10?

Fig, \$10\log_{256}(96)\approx\$ 8.231 bytes
]SeSn2@h$f

Try it online!
Outputs using inverted logic: positive integer for falsey, 0 for truthy
]SeSn2@h$f
         f # Digits of number
        $  # Reverse
    n2@    # For every other item in the list
       h   # Unhalve (double)
  eS       # Digit sum of each
 S         # Sum
]          # Take the last digit (equivalent to mod 10)

Vyxal, 8 bytes
fṘ⁽dẇṠ∑t

Try it Online!
Outputs 0 for truthy, any positive integer for falsey.
Explained
fṘ⁽dẇṠ∑t
fṘ       # reverse the list of digits of the input
  ⁽dẇ    # double each odd-indexed digit
     Ṡ∑t # sum each number, and take the tail of the sum

><>, 39 37 bytes
00@:}2%1+$c%*:a%$9)++{1+$1l3=.
n;a%0=

Try it online
Explanation
00                                 # init sum and counter to 0
  @:}2%1+                          # set counter to 1 if even and 2 if odd
         $c%*                      # mod current number by 12 and multiply by counter
               :a%$9)++            # sum digits and add to total sum
                       {1+$        # increment counter
                           1l3=.   # jump to next row if done, else skip init on 1st row
n;a%0=                             # print sum mod 10 == 0

Thunno 2 t!, 8 bytes
drŻɗ⁺×ʂS

Attempt This Online!
Or 10 bytes flagless:
drŻɗ⁺×ʂSt~

Attempt This Online!
Explanation
drŻɗ⁺×ʂSt~  # Implicit input
dr          # Cast to digits; reverse the list
  Ż         # Without popping, push [0..length)
   ɗ⁺       # Mod 2 of each; increment each
     ×      # Multiply elementwise
      ʂ     # Sum the digits of each number
       S    # Sum the resulting list
        t   # Pop and push the last digit
         ~  # And check if this equals 0
            # Implicit output

Pyth, 19 bytes (non-competing)
Non-competing since Pyth is newer than this challenge.
!%s.esj*b@S2kT_jQTT

A program that takes input of a string on STDIN and prints True or False as appropriate.
Try it online or verify all test cases
How it works
!%s.esj*b@S2kT_jQTT  Program. Input: Q
               jQT   Yield the base-10 representation of Q as a list, giving the digits
              _      Reverse
   .e                Enumerated map, with elements as b and indices as k:
          S2           Yield [1, 2]
         @  k          Modular indexing with k, yielding 1 for even indices and 2 for odd
                       indices
       *b              Multiply by b
      j      T         Yield the digits
     s                 Sum
  s                  Sum the resulting list
 %                T  Modulo 10
!                    Logical not, yielding True for 0 and False otherwise
                     Implicitly print

Tcl, 85 bytes
proc L n {expr ([regsub -all . [string rev $n] {+([incr i]%2?&:&*2%10+(&>4))}])%10<1}

Try it online!

Tcl, 86 bytes
proc L n {expr !(([regsub -all . [string rev $n] {+([incr i]%2?&:&*2%10+(&>4))}])%10)}

Try it online!
Tcl, 119 bytes
proc L n {expr !(([join [lmap a [lreverse [split $n ""]] {expr [incr i]%2?$a:[join [split [expr 2*$a] ""] +]}] +])%10)}

Try it online!

bash, 109 106 90 71 bytes
Output of 0 means True. Anything else means False.
for x in `rev<<<$1|fold -1`;{((s+=++i%2?x:(x*22/10)%10));}
echo $[s%10]

Try it online!
 90bytes
 Alt-90bytes-backwards

Burlesque, 33 bytes
riXX<-J2ENj2en2?***{XX++}ms10.%z?

Try it online!
ri         # Read input as int
XX         # Explode into digits
<-         # Reverse
J2EN       # Duplicate and take every 2nd starting from 1
j2en       # Take the other half
2?*        # Multiply each digit by 2
**         # Remerge arrays
{XX++}ms   # Sum the digits of multidigit and then sum result
10.%z?     # If result `mod` 10 is 0

Ruby, 67 66 bytes
-1 byte thanks to south
->n{n.digits.each_slice(2).map{_1+(2.*_2||0).digits.sum}.sum%10<1}

Attempt This Online!

(2.*_2||0) saves a byte

@south Nice. Thanks!

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


text:
fizz buzz in TMP
The Fizz Buzz problem is a very basic problem to solve that is used by some to weed out interviewees that don't know how to program.  The problem is:
Set N = [0,100]
Set F = x in N where x % 3 == 0
Set B = x in N where x % 5 == 0
Set FB = F intersect B

For all N:
  if x in F: print fizz
  if x in B: print buzz
  if x in FB: print fizzbuzz
  if x not in F|B|FB print x

The object of this modification of the Fizz Buzz problem is to perform the above algorithm using C++ templates such that as few runtime operations are necessary as can be done.
You can reduce N to a smaller range if you need to in order to fit within TMP objects where necessary.
This isn't expected to be a "golf".

You should say "Template Metaprogramming" rather than TMP, because most non-C++ people would have no idea what TMP is.

"weed out interviewees that don't know how to program" I didn't know that the average programmer needs to know Template Metaprogramming.

How do you define runtime operation? Assembler instruction? If so it might be a good idea to specify a compiler and platform so that there's no ambiguity.

@Alexandru: He said that the fizzbuzz problem is used to "weed out...", not that solving the fizzbuzz problem using Template Metaprogramming is.

Maybe you should mention that for all other numbers you need to print the number?

Backing up ChrisJester-Young: Imo TMP is temporary; template is TPL.

Possible duplicate of 1, 2, Fizz, 4, Buzz

Here's my attempt (had it lying around for a day or so, because I was unsure whether it was fit as a solution). Surprisingly the only bit I incorporated from @Chris was changing template<int N, int m3, int m5> to template<int N, int m3=N%3, int m5=N%5>
#include <iostream>

using namespace std;

template<int N, int m3=N%3, int m5=N%5>
struct fizzbuzz_print {
  static void print() {
    cout << N << '\n';
  }
};

template<int N, int m5>
struct fizzbuzz_print<N, 0, m5> {
  static void print() {
    cout << "fizz\n";
  }
};

template<int N, int m3>
struct fizzbuzz_print<N, m3, 0> {
  static void print() {
    cout << "buzz\n";
  }
};

template<int N>
struct fizzbuzz_print<N, 0, 0> {
  static void print() {
    cout << "fizzbuzz\n";
  }
};

template<int N>
struct fizzbuzz:public fizzbuzz<N-1> {
  fizzbuzz<N>() {
    fizzbuzz_print<N>::print();
  }
};

template<>
struct fizzbuzz<1> {
  fizzbuzz<1>() {
    fizzbuzz_print<1>::print();
  }
};

int main() {
  fizzbuzz<100> t;
}

Additionally, since this is my first attempt at TMP, any suggestions on improving my code would be appreciated.

Totally non-golfed solution:
template <int n, int m3 = n % 3, int m5 = n % 5>
struct FizzBuzz {
    static int value() {return n;}
};

template <int n, int m5>
struct FizzBuzz<n, 0, m5> {
    static char const* value() {return "Fizz";}
};

template <int n, int m3>
struct FizzBuzz<n, m3, 0> {
    static char const* value() {return "Buzz";}
};

template <int n>
struct FizzBuzz<n, 0, 0> {
    static char const* value() {return "FizzBuzz";}
};

Sample test code:
#include <iostream>

int
main()
{
    std::cout << FizzBuzz<1>::value() << '\n'
              << FizzBuzz<2>::value() << '\n'
              << FizzBuzz<3>::value() << '\n'
              << FizzBuzz<4>::value() << '\n'
              << FizzBuzz<5>::value() << '\n'
              << FizzBuzz<13>::value() << '\n'
              << FizzBuzz<14>::value() << '\n'
              << FizzBuzz<15>::value() << '\n'
              << FizzBuzz<16>::value() << '\n';
}

Okay, I finally got around to taking a shot at this. Unlike the previous solutions my solution builds the entire output string at compile time and the only run-time call is a single call to cout's << operator. I'm using boost::mpl to keep the code somewhat manageable.
#include <boost/mpl/string.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/mpl/char.hpp>
#include <boost/mpl/if.hpp>

using namespace boost::mpl;
using std::cout;

template<int n> struct IntToString {
    typedef typename push_back<typename IntToString<n/10>::str, char_<'0'+n%10> >::type str;
};

template<> struct IntToString<0> {
    typedef string<> str;
};

template<int n> struct FizzBuzzHelper {
    typedef typename push_back<typename IntToString<n>::str, char_<'\n'> >::type intstring;
    typedef typename if_< bool_<n%15==0>, string<'fizz','buzz','\n'>,
                          typename if_< bool_<n%5==0>, string<'buzz','\n'>,
                                        typename if_< bool_<n%3==0>, string<'fizz','\n'>,
                                                      intstring>::type >::type >::type str;
};

template<int n> struct FizzBuzz {
    typedef typename insert_range<typename FizzBuzz<n-1>::str,
                                  typename end<typename FizzBuzz<n-1>::str>::type,
                                  typename FizzBuzzHelper<n>::str>::type str;
};

template<> struct FizzBuzz<0> {
    typedef string<> str;
};

#include <iostream>

int main() {
    cout << c_str<FizzBuzz<9>::str>::value;
    return 0;
}

Sadly the code will blow up with boost::mpl::string complaining about too-large strings when using any n greater than 9.

362 characters.
#include <iostream>
#include <string>

using namespace std;

template<int N>
struct S {
    static string s, f, l;
};

template<int N>
string S<N>::s =
    N > 9
      ? S<N / 10>::s + S<N % 10>::s
      : string(1, '0' + N);

template<int N>
string S<N>::f =
    N % 15
      ? N % 5
          ? N % 3
              ? s
              : "fizz"
          : "buzz"
      : "fizzbuzz";

template<>
string S<0>::l = f;
template<int N>
string S<N>::l = S<N - 1>::l + "\n" + f;

int main() {
    cout << S<100>::l << endl;
    return 0;
}

Unless I'm missing something all of the operations happen at run time here.

@sepp2k: Do you mean ?:?  I thought that could be evaluated at compile time.  Of course, I do have a giant string concatenation happening at runtime here.

Primarily I meant the string construction and concatenation, but the ?: also doesn't have to happen at compile time (though it probably will).

source: Stack Exchange

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

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

sort: votes


text:
Find an unknown very large number
Let's suppose there is a finite unknown number n (n can be very large, does not necessarily fit 64-bits; think of BigInteger in Java or long in Python) and a function cmp(x) that returns true if x <= n.
Write a program to determine n in minimum number of calls to cmp.

The minimum number of calls will depend on the probability distribution of possible values of n.

How boundless? If it were infinitely large surely search time would be infinite too.

It is finite. Just that you don't know the limits. It's part of the problem.

A uniformly distributed ant? (Does that make any sense?)

Maybe use a very fast-growing function like Ackermann.

@Alexadru: The problem isn't that n is finite. The problem is that the set of numbers that n is a member of is unbounded. We need something like n < 10^10000 if we were to consider the "minumum" number of calls to cmp. You need to start at some finite number and consider growing from it. The problem is what number is optimal to start with. Without a bound, there is not optimal start (there might be unoptimal starts, but I haven't given it much thought). To sum things up, "minimum" and "unbounded" make this problem not well-defined.

Here's my solution in C, based on “binary search”:
#include <stdio.h>

int cmp(long x) {
    return (x <= 727695360);
}

int main(void)
{
    char *p = (char*)cmp;

    for (;;) {
        long x = *(long*)p++;
        if (cmp(x) && !cmp(x+1)) {
            printf("%ld\n", x);
            break;
        }
    }

    return 0;
}

Granted, there are a number of things that could go wrong, including:

cmp might compute its secret indirectly rather than using it as a literal.
The compiler might tweak the literal to generate faster or smaller code.  For example, x <= 727695360 could become x < 727695361.
The literal may be broken in half due to the target having a fixed-width instruction set.  I do not expect this code to work on PowerPC.
The target CPU might not like those unaligned long reads.  This code will cause an address error on a 68000 CPU.

I up voted the originality, but it doesn't work for more convoluted code such as static long n = time(0) + 12348821.

Double our guess until we exceed n, then do binary search.  This is a reasonable approach until n could be very large, at which point you probably want to do more than doubling at each step.
b=1;
while (cmp(b)) b *= 2;
a = b/2;
while (a < b-1) {  // invariant: a <= n < b
  m = (a+b)/2;
  if (cmp(m)) {
    a = m;
  } else {
    b = m;
  }
}
return a;

Clojure - 161 chars
Solution using BigInteger arithmetic and successive squaring / square roots to home in on answer. I believe this usually results in less comparisons than binary search for large values of n - typically close to the number of bits in the binary representation of the answer, which is the theoretical optimum if you only have a binary comparison available.
(use'clojure.contrib.math)(defn find[](loop[l 0 h nil](let[t(+(if h((exact-integer-sqrt(* l h))0)(* l l))1)](if(= l h)l(if(cmp t)(recur t h)(recur l(dec t)))))))

Expanded for readability:
(use 'clojure.contrib.math)
(defn find[]
  (loop [l 0 h nil]
    (let [t (+ (if h ((exact-integer-sqrt(* l h)) 0) (* l l)) 1)]
       (if (= l h) l
         (if (cmp t) (recur t h) (recur l (dec t)))))))

Note that the conciseness of the solution is considerably helped by the fact that Clojure automatically uses BigIntegers once values go outside the 64-bit long range.
In action:
; counter for compares
(def counter (atom 0))

; value to find
(def n 100000000000000000000000000000000000000000000000000000000)

; compare function
(defn cmp [x]
  (do
    (swap! counter inc)
    (<= x n)))

;let's find it!
(find)
=> 100000000000000000000000000000000000000000000000000000000

; how many calls to cmp?
@counter
=> 203

; how close to theoretical optimum?
(.bitLength 100000000000000000000000000000000000000000000000000000000)
=> 187

Assuming a uniform probability distribution:

Assign x to the maximum value n could be, y to the minimum value
Guess n=ceiling((x+y)/2)
If cmp returns true, y = the guess; else x = the guess - 1
If x=y, done (n=x=y); else goto (2)

We don't know the maximum, nor the minimum.

Then you can't have an optimal solution.  Consider one of the other answers where you start at 1 and do doubling -- it favours low numbers, so the greater the range the less optimal the solution is.

Couldn't you define the optimal solution as the one with the lowest average cmp() calls to range ratio?  It does seem like we would need to know how to model the distribution of possible ranges.

A solution in pseudocode (assuming x is nowhere near 0):
x=0
#Step 1: get upper and lower bounds on the number of digits
#double the number of digits until we go past the number
while cmp(2**(2**x)): x++
mindgt=2**(x-1)
maxdgt=2**x
#Step 2: find bounds on log(number)
while(maxdgt-mindgt!=1):
    n=(mindgt+maxdgt)/2
    if cmp(2**n):
        mindgt=n
    else:
        maxdgt=n
min=2**mindgt
max=2**maxdgt
#Step 3: straightforward binary search
while(max!=min):
    n=(max+min)/2
    if(cmp(n)):
        mindgt=n
    else:
        maxdgt=n-1
print max

For a value on the order of 1e40, this method takes 9 calls on step #1, 7 calls on step #2 and about 133 calls in step #3 for a total of 149.

Simple non-golf binary search:
num = 110134848298567717 # sample number
guess = 1
inc = 1
halved = 0
calls_to_cmp = 0

def my_cmp(x, n):
    global calls_to_cmp
    calls_to_cmp += 1
    return x <= n

while True:
    small = my_cmp(guess, num)
    if small: # add to guess, increase search field
        inc *= 2
        guess += inc
    else: # subtract from guess, decrease search field
        inc /= 2
        guess -= inc
    print "Guess: ", guess, ", inc: ", inc, "  calls so far: ", calls_to_cmp
    if inc == 0:
        break

print "Done."

One thing to consider is to initially try tripling or quadrupling for the first few loops: this will determine if the number is "small" (say under 1 million) or "large" and may speed the search up.

Just to be a cheeky bugger:
JavaScript, 34 chars
calls to cmp, technically 0
c=cmp
i=0
while(c(++i));
alert(i-1)

NOTE: JavaScript isn't a reasonable language to perform this in as it is restricted to 64-bit numeric values, so a string library would be necessary for managing larger numbers.

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


text:
Angle between the hands on a clock
Given the time in 24 hour format (2359 = 11:59pm) return the angle between the minute and hour hands on a standard clock (on the face plane, so don't just output 0).
Angles are to be returned in the unit of your choice, should be the smallest possible, and should be a positive number (negative angle converted to a positive value), i.e. you will never have an answer greater than 180 degrees or pi radians.
Some examples to check against (in degrees)

0000 = 0.0
0010 = 55.0
0020 = 110.0
0030 = 165.0
0040 = 140.0
0050 = 85.0
0150 = 115.0
0240 = 160.0
0725 = 72.5
1020 = 170.0
1350 = 115.0
1725 = 12.5

Note: There are a few that have rounding errors, I'm not sure how that should be handled; if we should force consistency across all values.

The clockwise angle, or the smallest of the two?

@SimpleCoder: Smallest, as the question says.

00:10 will be 0010 or 010?

It will be 0010 in 24 hour time @Nakilon

So I'm assuming the input is always a 4 character string?

That is correct @Mike

You should include some correct input/output examples including "difficult" input like 0001, 0633, etc...  I notice that many answers actually produce incorrect results.

@SimpleCoder: I think a "smallest positive" implies clockwise angle. Counterclockwise would correspond to negative angles. "Smallest" probably means "least multiple of 2*pi".

Why do everybody golf, when it was not supposed to golf? )

@Nakilon: Can't speak for anyone else, but in my case {1} I missed the tagging (need to establish new habits for this place), {2} golfing is why I came here, and {3} it's kind of simple for anything else, isn't it?

A few of the example answers are incorrect and the question is poorly worded ("positive angle only" for instance). I've corrected the examples, clarified the answer, and provided some more examples to highlight possible errors.

It appears that this wasn't originally code-golf. But now that it is, consider revising the accepted answer.

Oh boy, after 5 years my SO notification bar has been going crazy. What a surprising necro, haha. I'll check back in a few days to see if anyone can confirm the APL answer is correct (I'm traveling). I haven't been on this site for ages, but it would sure be nice to be able to mark golfs by language since this has since becoming golfing.

You can download a free APL interpreter from dyalog.com.

Haskell - 78 characters
q[h,i,m,n]=abs$((600*h+60*i-110*m-11*n-312)`mod`720)-360
c s=q$map fromEnum s

Note: My "unit of choice" is the "half-degree", of which there are 720 to the circle. With these units, the answer to the problem is always integral! :-)
Ex.:
> map c $ words "0000 0001 0010 0630 0633 2325 2345 2355 2359"
[0,11,110,30,3,335,165,55,11]
> map c $ words "0930 1845 0315 1742 2359"
[210,135,15,162,11]

Half-a-degree's. Nice.

c s=q$map fromEnum s can be c=q.map fromEnum. ( ... )`mod`720 can be mod( ... )720.

Golfscript, 42 bytes
2/~~\~60*+55*3600%.3600\-]{}$~;.10/'.'@10%

Outputs whole-a-degrees in float format.

+1 Great program! You can save a char by assigning 3600 to a variable and reusing that.

@w0lf ah good trick. I dont know any golf script, but thats bound to save like 2-5 bytes.

Perl, 58 characters
Perl is fun
perl -nlE "/(..)(..)/;$r=abs$1%12*30-5.5*$2;say+($r,360-$r)[$r>180]"

ES6, 52 50 bytes
t=>(t=(t-t.match`..`*40)*11%720,(t>360?720-t:t)/2)

Input string, output in degrees. If half degrees is acceptable, 46 bytes:
t=>(t=(t-t.match`..`*40)*11%720,t>360?720-t:t)

Edit: Saved 2 bytes by using a template string parameter to match.

TI-BASIC, 22 bytes
expr(Ans
sin⁻¹(sin(πfPart(11/6!(Ans-40int(sub(Ans

My unit is the "πth of a revolution", equal to 2 radians. The TI-83+ was introduced in 1996, making it much older than this challenge and thus eligible.
First we evaluate the string using expr(, then:
                                 sub(Ans   input/100. Don't ask why.
                             int(sub(Ans   Number of hours
                           40              Times 40
                       Ans-                Subtract from input. This converts to minutes.
                 11/6!(                    Multiply by 11/720 since 720/11 is the period.
           fPart(                          Take fractional part
sin⁻¹(sin(π                                Map [0,½] to [0,π/2] and [½,1] to [π/2,0].

All test cases have been verified.

wait what!? sub( is a string manipulation function... Yeah, I'm asking :P

sub( is a bit strange: it's the one only overloaded TI-BASIC command. When called with a number or list as its only argument, it calculates x/100, vectorized on lists. See here.

@DanMcGrath I've revised my answer to take input as a string. If an integer is acceptable, I'll revert.

Perl, 61 characters:
sub f{$a=abs(int($_[0]/200)-($_[0]%60)/5);($a>6?12-$a:$a)*30}

Your answer is wrong: 1. It generates wrong results for 1059, 1058, etc. 2. 0020 should be 110 degrees, 0030 should be 165, 0040 should be 140, and 0050 should be 85. (The hour hand moves 30 degree every hour---thus, it moves half a degree every minute.)

Ruby 1.9.2p136 : 78 74
def a(t)m=t[2,2].to_f
180-((m*6-(m/60+t[0,2].to_f%12)*30).abs-180).abs
end

Sample output:
["0000", "0010", "0020", "0030", "0040",
  "0050", "0150", "0240", "0725", "1020",
  "1350", "1725"].each do |time|
  puts "#{time} = #{a(time)}"
end
# Output
0000 = 0.0
0010 = 55.0
0020 = 110.0
0030 = 165.0
0040 = 140.0
0050 = 85.0
0150 = 115.0
0240 = 160.0
0725 = 72.5
1020 = 170.0
1350 = 115.0
1725 = 12.5

You output has the hour hand fixed on the hour marks rather than sweeping during the hour. Most answers have been assuming a uniform sweep for the hour hand.

Yep, and it also doesn't work if the hour hand is at say 1 and the minute hand is at 11. I fell asleep before fixing it...

Fixed and updated.

C99, 86 78 bytes
My units are twelfths of revolutions (so 3 corresponds to 90°)

#include<math.h>
float f(int t){return fabs(remainder((t+t%100/1.5)*.11,12));}

Equivalently, in C++14, for 76 bytes:

#include<cmath>
auto f(int t){return fabs(remainder((t+t%100/1.5)*.11,12));}

BSD and SVID platforms have remd as an alias for remainder (to save 5 more), but I'm sticking with standard C and C++.
Explanation
We convert sexagesimal seconds to centihours by adding t%100/1.5 (so 0030 becomes 0050 etc), and divide by 100 to get hours. Coincidence of hands occurs 11 times every 12 hours, so multiply by 11 and divide by 12; we take the remainder in the range [-6,+6], and return its absolute value.
Test program
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char**argv)
{
    int i;
    for (i = 1;  i < argc;  ++i)
        printf("%4s: %f\n", argv[i], f(atoi(argv[i])));
    return 0;
}

Test output:
A minimum around 12:00:

1150: 1.833333
1151: 1.650000
1152: 1.466667
1153: 1.283333
1154: 1.100000
1155: 0.916667
1156: 0.733333
1157: 0.550000
1158: 0.366667
1159: 0.183333
1200: 0.000000
1201: 0.183333
1202: 0.366667
1203: 0.550000
1204: 0.733333
1205: 0.916667
1206: 1.100000
1207: 1.283333
1208: 1.466667
1209: 1.650000
1210: 1.833333

And a maximum around 6:00:

0555: 5.083333
0556: 5.266667
0557: 5.450000
0558: 5.633333
0559: 5.816667
0600: 6.000000
0601: 5.816667
0602: 5.633333
0603: 5.450000
0604: 5.266667
0605: 5.083333

You can squeeze more bytes by declaring the function anonymous and generic, also returning via reference parameter saves bytes: https://codegolf.stackexchange.com/questions/137549/dropsort-it-like-its-hot/137854#137854

Dyalog APL, 34 32 27 25 characters
Full program. Prompts for 4-character string from stdin. Prints radians to stdout.
¯2○2○○360÷⍨11×60⊥⍎¨↓2 2⍴⎕

Try it online!
The angle changes linearly with the time, going through 22×360° every 1440 minutes, or 5.5°/min.
Method:

Take input: ⎕

Make into 2-by-2 table: 2 2⍴

Split into rows: ↓

Evaluate each: ⍎¨

Convert to minutes: 60⊥

Convert to degrees and then to radians (5.5t × π/180 = 11t × π/360): ○360÷⍨11×

arccos cos to invert after π/2: ¯2○2○

Test cases can be verified by converting the result into degrees:
      angle←  {¯2○2○○360÷⍨11×60⊥⍎¨↓2 2⍴⍵}
      rads2degs←{180×⍵÷○1}

      rads2degs angle ¨ '0000' '0010' '0020' '0030' '0040' '0050' '0150' '0240' '0725' '1020' '1350' '1725'
0 55 110 165 140 85 115 160 72.5 170 115 12.5

Try it online!

Perl, 91 chars
#!perl -n
($h,$m)=/(..)(..)/;$h=$h%12+$m/60;$h=abs($h*30-$m*6);printf'%f
',$h>180?360-$h:$h

Python, 82 bytes
def a(t):
    o=abs(30*(int(t[:1])%12)-5.5*int(t[2:]));return o if o<=180 else 360-o

With some help from the python golfing question I've brought it down to 76:
def a(t):
    o=abs(30*(int(t[:1])%12)-5.5*int(t[2:]));return [o,360-o][o>180]

no need for a space itn return [. You should convert to a lambda function anyhow if you can (for golfing)

PHP, 80 Characters
<?=($i=$argv[1])&&($n=abs(($i[0].$i[1])%12*30-($i[2].$i[3])*5.5))>180?360-$n:$n;

Can be run from CLI php /script_name input
Explanation:
<?=                           // output result to console
    ($i = $argv[1]) && (      // $argv is an array containing CLI parameters (0: script name, 1: first parameter, etc.)
        $n = abs(             // absolute value to deal with negative numbers
            ($i[0] . $i[1])   // get hours - the first two characters from the input (0 and 1)
                % 12 * 30     // modulus 12 to deal with PM hours (13-23) multiplied by 360/12 = 30 degrees
            - ($i[2] . $i[3]) // get minutes - the subsequent characters from the input (2 and 3)
                * 5.5)        // multiply minutes by 5.5 (1 minute is 360/60 = 6 degrees
                              // and the hour hand moves every minute by 30/60 = 0.5 degrees which we subtract)
        ) > 180               // compare obtained result to 180
    ? 360 - $n                // if the result is greater subtract it from 360
    : $n;                     // if it's less - output as it is

Test cases (input output)
0000 0
0010 55
0155 87.5
0240 160
1234 173
2155 32.5
2222 179

Have I missed something? This works correctly for all examples given in the question, so can't imagine why was downvoted.

Welcome to Programming Puzzles & Code Golf! Sorry your first post got downvoted; I see no reason why it should be. Though if you could add some explanation of the code, that would be nice. :)

Thanks guys. Added code explanation. Maybe someone's angry that we've resurrected a five year old thread :)

Matlab/Octave, 56 bytes
An anonymous function accepting a string, output is in degrees.
@(i)180-abs(mod((i-48)*[600;60;10;1],720/11)-360/11)*5.5

Python, 106 bytes
Non-golf solution:
def angle_24hr(time_str):
    hour, minute = int(time_str[0:1]) % 12, int(time_str[2:3]) % 60
    angle_dist = lambda a, b: ((a + (180 - b)) % 360) - 180
    return angle_dist(((hour * 30) + (minute * 0.5)), minute * 6) * 10

In a more obscure/obfuscated form (admittedly, one of my first code golfs):
ad=lambda a,b:((a-b+180)%360)-180;x=int;ag=lambda t:10*ad((x(t[0:1])%12)*60+x(t[2:3]),(x(t[2:3]*12)%60)*6)

(what's the point of obfuscating Python?)
If it's necessary for the angles to be purely positive you can remove the -180 term.

Your answer is wrong: 0020 should be 110 degrees, 0030 should be 165, 0040 should be 140, and 0050 should be 85. (The hour hand moves 30 degree every hour---thus, it moves half a degree every minute.)

@Chris, why 110 degrees for 0020? Am I missing something: hour hand is at 0, minute hand is at 20*6 = 120...?

The hour hand is not at 0 when the minute hand is at 20. It's at one-third between 12 and 1.

@Chris Of course, now it seems obvious to me. Back in a sec with fixed code.

Depends on your clock. My clock only moves the hour hand on full hours. Since it wasn't specified in the question it wouldn't make much sense to do it the hard way would it? OK... I'll just admit it... I screwed up to... doh!

c99 -- 204 necessary characters (keeps getting worse as I fix bugs)
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){char b[5]={0};fgets(b,5,stdin);int a,h,m=atoi(b+2);b[2]=0;
h=(atoi(b)*60+m)%720;m*=12;a=abs((h-m)%720);a=a>360?720-a:a;printf("%i\n",a);}

Discussion:
The problem turns out to be harder than it looks. The critical issue is what is meant by "smallest positive angle". I've interpreted that the mean a value between [0,180] degrees inclusive (because the problem does not specify which hand to start from when measuring).
To validate this behavior look for places when the hands pass the straight-apart position (such as around 00:33-00:35), and places where they cross-over as around 06:33.
I've also chosen to have a steadily sweeping hour hand, as most modern clocks seem to use that method.
I've adopted MtnViewMark clever trick of using half-degrees as the base unit.
I've suffered the usual problem with c: the preprocessor commands to get the libraries eat up a lot of characters.
Readable and commented:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
  char b[5]={0};
  fgets(b,5,stdin); /* assumes single byte charaters */
/*   printf("'%s'\n",b); */
  int a,h,m=atoi(b+2); /* minutes */
  b[2]=0;
  h=(atoi(b)*60+m)%720;  /* hour had position in hald-degrees */
  m*=12;                 /* minute hand position in half degrees */
/*   printf("%3i\t%3i\n",h,m); */
/*   printf("%i\n", h-m ); */
/*   printf("%i\n",(h-m)%720 ); */
  a=abs((h-m)%720);
/*   printf("%i\n",   a ); */
  a=a>360?720-a:a;
  printf("%i\n",a);
}

Validation:
$gcc -c99 golf_clock_angle.c
$wc golf_clock_angle.c
  5  11 206 golf_clock_angle.c
$!for
for t in $(cat clock_test_times.txt); do echo $t $(echo $t|./a.out); done
0000 0
0001 11
0002 22
0010 110
0015 165
0030 330
0033 357
0034 346
0035 335
0045 225
0630 30
0633 3
0634 14
2324 324
2325 335
2355 55
2359 11

Your answers are way off. For instance at 0010 the minute hand will be at 60 degrees and the hour hand will be at 5 degrees. There are 55 degrees between them. In fact a lot of your angles look doubled.

@Mike: Note the units. I've adopted MntViewMark's convention of expressing answers in half-degrees.

Ah, seems like cheating to me... let me see if I can abuse it too. ;)

Says "Angles are to be returned in the unit of your choice"... ;-)

@MntViewMark: Yep. But I'll bet Dan was thinking "degrees or radians" when he wrote that.

Mathematica
Grid@Prepend[
Table[{Row[{Quotient[x, 60] /. {0 -> 12}, ":", If[Mod[x, 60] < 10, "0", ""], Mod[x, 60]}],
x, N[x/2, 3], Mod[6 x, 360],
IntegerPart[Min[Abs[x/2 - Mod[6 x, 360]], 360 - Abs[x/2 - Mod[6 x, 360]]]]},
{x, 0, 12*60}], {"time", "elapsed min", "hourhand deg", "min deg", "diff deg"}]

Partial output in table

Graphs
Plot[{ x/2, Mod[6 x, 360], Min[Abs[x/2 - Mod[6 x, 360]], 360 - Abs[x/2 - Mod[6 x, 360]]]}, {x, 0, 12*60},PlotStyle -> {Green, Blue, {Thick, Red}},AxesLabel -> {"time (hs)", "degrees"},GridLinesStyle -> Directive[Dotted, Gray],Ticks -> {Table[{60 k, k}, {k, 0, 12}], Table[30 k, {k, 0, 12}]},GridLines -> {Table[60 k, {k, 0, 12}], None}]

The green line shows the angle of the hour hand, as measured in degrees from 12 o'clock, clockwise. The blue line shows the corresponding angle for the minute hand.
The red curve shows the difference between the minute and hour hands in degrees; it always uses the interior angle.

It does not seem like an attempt to golf the code has been made, which makes the answer in its current form  invalid.

C++, 175 174 166 156 Characters
#include <iostream>
#include <cmath>
int main(){int m,h;std::cin>>h;m=h%100;h=(h-m)/100;h=h>11?h=h-12:h;h=std::abs(h*60-m*11);std::cout<<std::min(720-h,h);}

Using "half degree's" as my unit of choice :D
Try it Online!

C# (.NET Core), 87 bytes
t=>{var i=int.Parse(t);double d=i/100%12*30-i%100*5.5,r=d<0?-d:d;return r>180?360-r:r;}

Try it online!
I'm sure there are possible improvements that I have missed.
DeGolfed
t=>{
    var i = int.Parse(t);
    // The hour angles minus the minute angles
    double d = i / 100 % 12 * 30 -
               i % 100 * 5.5,
    // account for this possibly being a negative angle
           r = d < 0? -d : d;

    // Get the smaller of the two possible rotational angles
    return r > 180? 360-r : r;
}

JavaScript (ES6), 75 bytes
x=>Math.min(x=((x=x.match(/\d\d/g))[0]*60+x[1]*1)*5.5%360,360-x).toFixed(1)

This question needed a JavaScript solution.

SmileBASIC, 60 bytes
INPUT T
A=ABS(T DIV 100*60-T MOD 100*11)?A/2+(360-A)*(A>360)

05AB1E, 23 bytes
2ôć12%30*s11;*αD360α)˜ß

Outputs degrees like the challenge description.
Port of @Juan's Python answer.
Try it online or verify all test cases.
Explanation:
2ô                  # Split the (implicit) input in pieces of 2
                    #  i.e. "0150" → ['01','50']
  ć                 # Head extracted
                    #  i.e. ['01','50'] → ['50'] and '01' are pushed to the stack
   12%              # Take the hours modulo 12
      30*           # Multiplied by 30
                    #  i.e. '01' → 30
  s                 # Swap so the minutes are now at the top of the stack
   11;*             # And multiple it by 5.5
                    #  i.e. ['50'] → [275.0]
       α            # Calculate the absolute difference between the two values
                    #  30 and [275.0] → [245.0]
        D           # Duplicate this value
         360α       # Calculate the absolute difference between this value and 360
                    #  i.e. [245.0] → [115.0]
             )      # Wrap the entire stack to a list
                    #  i.e. [245.0] and [115.0] → [[245.0],[115.0]]
              ˜     # Flatten this list (necessary due to the head extracted)
                    #  i.e. [[245.0],[115.0]] → [245.0,115.0]
               ß    # And take the smallest value of the two (output implicitly)
                    #  i.e. [245.0,115.0] → 115.0

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


text:
Fast line drawing algorithm
The task is to find a way to draw a horizontal line in an array of 16-bit integers.
We're assuming a 256x192 pixel array with 16 pixels per word. A line is a contiguous run of set (1) bits. Lines can start in the middle of any word, overlap any other words, and end in any word; they may also start and end in the same word. They may not wrap on to the next line. Hint: the middle words are easy - just write 0xffff, but the edges will be tricky, as will handling the case for the start and end in the same word. A function/procedure/routine must take an x0 and x1 coordinate indicating the horizontal start and stop points, as well as a y coordinate.
I exclude myself from this because I designed a nearly identical algorithm myself for an embedded processor but I'm curious how others would go about it. Bonus points for using relatively fast operations (for example, a 64 bit multiply or floating point operation wouldn't be fast on an embedded machine but a simple bit shift would be.)

I started a discussion about performance measurements on meta - you're invited.

how was winner chosen?

This code assumes that both x0 and x1 are inclusive endpoints, and that words are little endian (i.e. the (0,0) pixel can be set with array[0][0]|=1).
int line(word *array, int x0, int x1, int y) {
  word *line = array + (y << 4);
  word *start = line + (x0 >> 4);
  word *end = line + (x1 >> 4);
  word start_mask = (word)-1 << (x0 & 15);
  word end_mask = (unsigned word)-1 >> (15 - (x1 & 15));
  if (start == end) {
    *start |= start_mask & end_mask;
  } else {
    *start |= start_mask;
    *end |= end_mask;
    for (word *p = start + 1; p < end; p++) *p = (word)-1;
  }
}

How fast is it?

Python
The main trick here is to use a lookup table to store bitmasks of the pixels. This saves a few operations. A 1kB table is not that large even for an embedded platform these days
If space is really tight, for the price of a couple of &0xf the lookup table can be reduced to just 64B
This code is in Python, but would be simple to port to any language that supports bit operations.
If using C, you could consider unwinding the loop using the switch from Duff's device. Since the line is maximum of 16 words wide, I would extend the switch to 14 lines and dispense with the while altogether.
T=[65535, 32767, 16383, 8191, 4095, 2047, 1023, 511,
   255, 127, 63, 31, 15, 7, 3, 1]*16
U=[32768, 49152, 57344, 61440, 63488, 64512, 65024, 65280,
   65408, 65472, 65504, 65520, 65528, 65532, 65534, 65535]*16

def drawline(x1,x2,y):
    y_=y<<4
    x1_=y_+(x1>>4)
    x2_=y_+(x2>>4)
    if x1_==x2_:
        buf[x1_]|=T[x1]&U[x2]
        return
    buf[x1_]|=T[x1]
    buf[x2_]|=U[x2]
    x1_+=+1
    while x1_<x2_:
        buf[x1_] = 0xffff
        x1_+=1

#### testing code ####

def clear():
    global buf
    buf=[0]*192*16

def render():
    for y in range(192):
        print "".join(bin(buf[(y<<4)+x])[2:].zfill(16) for x in range(16))

clear()
for y in range(0,192):
    drawline(y/2,y,y)
for x in range(10,200,6):
    drawline(x,x+2,0)
    drawline(x+3,x+5,1)
for y in range(-49,50):
    drawline(200-int((2500-y*y)**.5), 200+int((2500-y*y)**.5), y+60)
render()

Here is a C version of my Python answer using the switch statement instead of the while loop and reduced indexing by incrementing a pointer instead of the array index
The size of the lookup table can be substantially reduced by using T[x1 & 0xf] and U[x2 & 0xf] for a couple of extra instructions
#include <stdio.h>
#include <math.h>

unsigned short T[] = {0xffff, 0x7fff, 0x3fff, 0x1fff, 0x0fff, 0x07ff, 0x03ff, 0x01ff,
                      0x00ff, 0x007f, 0x003f, 0x001f, 0x000f, 0x0007, 0x0003, 0x0001,
                      0xffff, 0x7fff, 0x3fff, 0x1fff, 0x0fff, 0x07ff, 0x03ff, 0x01ff,
                      0x00ff, 0x007f, 0x003f, 0x001f, 0x000f, 0x0007, 0x0003, 0x0001,
                      0xffff, 0x7fff, 0x3fff, 0x1fff, 0x0fff, 0x07ff, 0x03ff, 0x01ff,
                      0x00ff, 0x007f, 0x003f, 0x001f, 0x000f, 0x0007, 0x0003, 0x0001,
                      0xffff, 0x7fff, 0x3fff, 0x1fff, 0x0fff, 0x07ff, 0x03ff, 0x01ff,
                      0x00ff, 0x007f, 0x003f, 0x001f, 0x000f, 0x0007, 0x0003, 0x0001,
                      0xffff, 0x7fff, 0x3fff, 0x1fff, 0x0fff, 0x07ff, 0x03ff, 0x01ff,
                      0x00ff, 0x007f, 0x003f, 0x001f, 0x000f, 0x0007, 0x0003, 0x0001,
                      0xffff, 0x7fff, 0x3fff, 0x1fff, 0x0fff, 0x07ff, 0x03ff, 0x01ff,
                      0x00ff, 0x007f, 0x003f, 0x001f, 0x000f, 0x0007, 0x0003, 0x0001,
                      0xffff, 0x7fff, 0x3fff, 0x1fff, 0x0fff, 0x07ff, 0x03ff, 0x01ff,
                      0x00ff, 0x007f, 0x003f, 0x001f, 0x000f, 0x0007, 0x0003, 0x0001,
                      0xffff, 0x7fff, 0x3fff, 0x1fff, 0x0fff, 0x07ff, 0x03ff, 0x01ff,
                      0x00ff, 0x007f, 0x003f, 0x001f, 0x000f, 0x0007, 0x0003, 0x0001,
                      0xffff, 0x7fff, 0x3fff, 0x1fff, 0x0fff, 0x07ff, 0x03ff, 0x01ff,
                      0x00ff, 0x007f, 0x003f, 0x001f, 0x000f, 0x0007, 0x0003, 0x0001,
                      0xffff, 0x7fff, 0x3fff, 0x1fff, 0x0fff, 0x07ff, 0x03ff, 0x01ff,
                      0x00ff, 0x007f, 0x003f, 0x001f, 0x000f, 0x0007, 0x0003, 0x0001,
                      0xffff, 0x7fff, 0x3fff, 0x1fff, 0x0fff, 0x07ff, 0x03ff, 0x01ff,
                      0x00ff, 0x007f, 0x003f, 0x001f, 0x000f, 0x0007, 0x0003, 0x0001,
                      0xffff, 0x7fff, 0x3fff, 0x1fff, 0x0fff, 0x07ff, 0x03ff, 0x01ff,
                      0x00ff, 0x007f, 0x003f, 0x001f, 0x000f, 0x0007, 0x0003, 0x0001,
                      0xffff, 0x7fff, 0x3fff, 0x1fff, 0x0fff, 0x07ff, 0x03ff, 0x01ff,
                      0x00ff, 0x007f, 0x003f, 0x001f, 0x000f, 0x0007, 0x0003, 0x0001,
                      0xffff, 0x7fff, 0x3fff, 0x1fff, 0x0fff, 0x07ff, 0x03ff, 0x01ff,
                      0x00ff, 0x007f, 0x003f, 0x001f, 0x000f, 0x0007, 0x0003, 0x0001,
                      0xffff, 0x7fff, 0x3fff, 0x1fff, 0x0fff, 0x07ff, 0x03ff, 0x01ff,
                      0x00ff, 0x007f, 0x003f, 0x001f, 0x000f, 0x0007, 0x0003, 0x0001,
                      0xffff, 0x7fff, 0x3fff, 0x1fff, 0x0fff, 0x07ff, 0x03ff, 0x01ff,
                      0x00ff, 0x007f, 0x003f, 0x001f, 0x000f, 0x0007, 0x0003, 0x0001};

unsigned short U[] = {0x8000, 0xc000, 0xe000, 0xf000, 0xf800, 0xfc00, 0xfe00, 0xff00,
                      0xff80, 0xffc0, 0xffe0, 0xfff0, 0xfff8, 0xfffc, 0xfffe, 0xffff,
                      0x8000, 0xc000, 0xe000, 0xf000, 0xf800, 0xfc00, 0xfe00, 0xff00,
                      0xff80, 0xffc0, 0xffe0, 0xfff0, 0xfff8, 0xfffc, 0xfffe, 0xffff,
                      0x8000, 0xc000, 0xe000, 0xf000, 0xf800, 0xfc00, 0xfe00, 0xff00,
                      0xff80, 0xffc0, 0xffe0, 0xfff0, 0xfff8, 0xfffc, 0xfffe, 0xffff,
                      0x8000, 0xc000, 0xe000, 0xf000, 0xf800, 0xfc00, 0xfe00, 0xff00,
                      0xff80, 0xffc0, 0xffe0, 0xfff0, 0xfff8, 0xfffc, 0xfffe, 0xffff,
                      0x8000, 0xc000, 0xe000, 0xf000, 0xf800, 0xfc00, 0xfe00, 0xff00,
                      0xff80, 0xffc0, 0xffe0, 0xfff0, 0xfff8, 0xfffc, 0xfffe, 0xffff,
                      0x8000, 0xc000, 0xe000, 0xf000, 0xf800, 0xfc00, 0xfe00, 0xff00,
                      0xff80, 0xffc0, 0xffe0, 0xfff0, 0xfff8, 0xfffc, 0xfffe, 0xffff,
                      0x8000, 0xc000, 0xe000, 0xf000, 0xf800, 0xfc00, 0xfe00, 0xff00,
                      0xff80, 0xffc0, 0xffe0, 0xfff0, 0xfff8, 0xfffc, 0xfffe, 0xffff,
                      0x8000, 0xc000, 0xe000, 0xf000, 0xf800, 0xfc00, 0xfe00, 0xff00,
                      0xff80, 0xffc0, 0xffe0, 0xfff0, 0xfff8, 0xfffc, 0xfffe, 0xffff,
                      0x8000, 0xc000, 0xe000, 0xf000, 0xf800, 0xfc00, 0xfe00, 0xff00,
                      0xff80, 0xffc0, 0xffe0, 0xfff0, 0xfff8, 0xfffc, 0xfffe, 0xffff,
                      0x8000, 0xc000, 0xe000, 0xf000, 0xf800, 0xfc00, 0xfe00, 0xff00,
                      0xff80, 0xffc0, 0xffe0, 0xfff0, 0xfff8, 0xfffc, 0xfffe, 0xffff,
                      0x8000, 0xc000, 0xe000, 0xf000, 0xf800, 0xfc00, 0xfe00, 0xff00,
                      0xff80, 0xffc0, 0xffe0, 0xfff0, 0xfff8, 0xfffc, 0xfffe, 0xffff,
                      0x8000, 0xc000, 0xe000, 0xf000, 0xf800, 0xfc00, 0xfe00, 0xff00,
                      0xff80, 0xffc0, 0xffe0, 0xfff0, 0xfff8, 0xfffc, 0xfffe, 0xffff,
                      0x8000, 0xc000, 0xe000, 0xf000, 0xf800, 0xfc00, 0xfe00, 0xff00,
                      0xff80, 0xffc0, 0xffe0, 0xfff0, 0xfff8, 0xfffc, 0xfffe, 0xffff,
                      0x8000, 0xc000, 0xe000, 0xf000, 0xf800, 0xfc00, 0xfe00, 0xff00,
                      0xff80, 0xffc0, 0xffe0, 0xfff0, 0xfff8, 0xfffc, 0xfffe, 0xffff,
                      0x8000, 0xc000, 0xe000, 0xf000, 0xf800, 0xfc00, 0xfe00, 0xff00,
                      0xff80, 0xffc0, 0xffe0, 0xfff0, 0xfff8, 0xfffc, 0xfffe, 0xffff,
                      0x8000, 0xc000, 0xe000, 0xf000, 0xf800, 0xfc00, 0xfe00, 0xff00,
                      0xff80, 0xffc0, 0xffe0, 0xfff0, 0xfff8, 0xfffc, 0xfffe, 0xffff};

unsigned short buf[192*16];

void clear(){
    int i;
    for (i=0; i<192*16; i++) buf[i]==0;
}

void render(){
    int x,y;
    for (y=0; y<192; y++){
        for (x=0; x<256; x++) printf("%d", (buf[(y<<4)+(x>>4)]>>(15-(x&15)))&1);
        printf("\n");
    }
}

void drawline(int x1, int x2, int y){
    int y_ = y<<4;
    int x1_ = y_+(x1>>4);
    int x2_ = y_+(x2>>4);
    unsigned short *p = buf+x1_;

    if (x1_==x2_){
        *p|=T[x1]&U[x2];
        return;
        }

    *p++|=T[x1];
    switch (x2_-x1_){
    case 14: *p++ = 0xffff;
    case 13: *p++ = 0xffff;
    case 12: *p++ = 0xffff;
    case 11: *p++ = 0xffff;
    case 10: *p++ = 0xffff;
    case 9: *p++ = 0xffff;
    case 8: *p++ = 0xffff;
    case 7: *p++ = 0xffff;
    case 6: *p++ = 0xffff;
    case 5: *p++ = 0xffff;
    case 4: *p++ = 0xffff;
    case 3: *p++ = 0xffff;
    case 2: *p++ = 0xffff;
    case 1: *p++ = U[x2];
    }
}

int main(){
    int x,y;
    clear();

    for (y=0; y<192; y++){
        drawline(y/2,y,y);
    }

    for (x=10; x<200; x+=6){
        drawline(x,x+2,0);
        drawline(x+3,x+5,1);
    }

    for (y=-49; y<50; y++){
        x = sqrt(2500-y*y);
        drawline(200-x, 200+x, y+60);
    }
    render();
    return 0;
    }

How fast is it?

@user unknown, How long is a piece of string? I think it should be faster than the accepted answer because it uses a lookup table to reduce the amount of work slightly. Why don't you try them out and let us know what you find?

Scala,  7s / 1M lines 4.1s / 1M lines
// declaration and initialisation of an empty field:
val field = Array.ofDim[Short] (192, 16)

first implementation:
// util-method: set a single Bit:
def setBit (x: Int, y: Int) =
  field (y)(x/16) = (field (y)(x/16) | (1 << (15 - (x % 16)))).toShort
def line (x0: Int, x1: Int, y: Int) =
  (x0 to x1) foreach (setBit (_ , y))

After eliminating the inner method call, and replacing the for- with a while-loop, on my 2Ghz Single Core with Scala 2.8 it absolves 1 Mio. Lines in 4.1s sec. instead of initial 7s.
  def line (x0: Int, x1: Int, y: Int) = {
    var x = x0
    while (x < x1) {
      field (y)(x/16) = (field (y)(x/16) | (1 << (15 - (x % 16)))).toShort
      x += 1
    }
  }

Testcode and invocation:
// sample invocation:
line (12, 39, 3)
// verification
def shortprint (s: Short) = s.toBinaryString.length match {
  case 16 => s.toBinaryString
  case 32 => s.toBinaryString.substring (16)
  case x  => ("0000000000000000".substring (x) + s.toBinaryString)}

field (3).take (5).foreach (s=> println (shortprint (s)))
// result:
0000000000001111
1111111111111111
1111111100000000
0000000000000000
0000000000000000

Performance testing:
  val r = util.Random

  def testrow () {
    val a = r.nextInt (256)
    val b = r.nextInt (256)
    if (a < b)
      line (a, b, r.nextInt (192)) else
        line (b, a, r.nextInt (192))
  }

  def test (count: Int): Unit = {
    for (n <- (0 to count))
      testrow ()
  }

  // 1 mio tests
  test (1000*1000)

Tested with the unix tool time, comparing the user-time, including startup-time, compiled code, no JVM-start-up phase.
Increasing the number of lines shows, that for every new million, it needs an extra 3.3s.


text:
Fast Topswops calculation
From AZSPCS:
Suppose you have a deck containing n cards. Each card contains a number from 1 to n, and each number appears on exactly one card. You look at the number on the top card -- let's says it's k -- and then reverse the order of the top k cards. You continue this procedure -- reading the top number and then reversing the corresponding number of cards -- until the top card is 1.
Write the fastest program to compute the number of reversals for a given deck. Note that if you are participating in the contest you are not allowed to post your code (and thus I will not post my code yet).

What is the input/output model? Any language restrictions? How will you determine how fast each entry is?

There could be a dedicated stackexchange for azspcs ;)

So are we allowed to post solutions or not?

Yes. The contest has finished.

The link to azspcs links to a page which is out of order. And it seems a meta-tag, which doesn't describe the puzzle. The tag should, perhaps, be removed.

JavaScript
function(d){for(t=0;x=(n=d[0])-1;t++)for(i=0;i<n/2;i++){m=d[x-i];d[x-i]=d[i];d[i]=m}return t}

You pass it the deck, like so:
f([3, 2, 1]) // 1
f([2, 3, 1]) // 2
f([1, 2, 3]) // 0

So you're the winner! :)

Scala: (This isn't a golf - is it?)
def transform (l: List[Int], sofar: Int = 0) : Int =
  if (l(0) == 1) sofar else transform (l.take (l(0)).reverse ::: l.drop (l(0)), sofar + 1)

Complete application with testcase and stopwatch, including the shuffling of the Deck:
object DeckReverse extends Application {

  def transform (l: List[Int], sofar: Int = 0) : Int =
    if (l(0) == 1) sofar else transform (l.take (l(0)).reverse ::: l.drop (l(0)), sofar + 1)

  def stopwatch (count: Int, size: Int) = {
    val li = (1 until size).toList
    val r = util.Random

    val start = System.currentTimeMillis ()
    (0 until count).foreach (_ => transform (r.shuffle (li)))
    val stop = System.currentTimeMillis ()

    println ("count: " + count + "\tsize: " + size + "\tduration: " + (stop - start) + " msecs")
  }

  stopwatch (1000, 100)
}

count: 1000  size: 100  duration: 1614 msecs
machine: Single Pentium M 2Ghz

Python, 84 Chars
Golfing anyway... I'm using the numbers 0 through n-1.  Assuming the array is stored in a variable x, it takes me 84 chars of Python.
while x[0]:x[:x[0]+1]=x[x[0]::-1]

However, performance is pretty bad due to memory abuse.

Perl 5, 58 + 2 (-ap) = 60 bytes
++$\&&(@F[0..$F[0]-1]=reverse@F[0..$F[0]-1])while$F[0]-1}{

Try it online!

C
int revno(int* deck, int n) {
  int k,j,r=0;
  for(;;) {
    k=*deck;
    if (k==1) {
      return r;
    }
    for (j=0; j<k/2; j++) {
      int tmp=deck[j];
      deck[j]=deck[k-j];
      deck[k-j]=tmp;
    }
    r++;
  }
}

deck is a pointer to an integer array representing the decks. n is the number of the cards. Obviously memory safety is the task of the caller.
It is probably nearing the fastest algorithm on recent computers and on a high-level language. Only with asm-level tricks could it be made faster, but not heavily even with them.