The ancient Greeks had these things called singly and doubly even numbers. An example of a singly even number is 14. It can be divided by 2 once, and has at that point become an odd number (7), after which it is not divisible by 2 anymore. A doubly even number is 20. It can be divided by 2 twice, and then becomes 5.

Your task is to write a function or program that takes an integer as input, and outputs the number of times it is divisible by 2 as an integer, in as few bytes as possible. The input will be a nonzero integer (any positive or negative value, within the limits of your language).

Test cases:

14 -> 1

20 -> 2

94208 -> 12

7 -> 0

-4 -> 2

The answer with the least bytes wins.

Tip: Try converting the number to base 2. See what that tells you.

  • 11
    \$\begingroup\$ @AlexL. You could also look at it is never becoming odd, so infinitely even. I could save a few bytes if a stack overflow is allowed ;) \$\endgroup\$ – Geobits Feb 12 '16 at 16:43
  • 1
    \$\begingroup\$ The input will be a nonzero integer Does this need to be edited following your comment about zero being a potential input? \$\endgroup\$ – trichoplax Feb 13 '16 at 1:55
  • 2
    \$\begingroup\$ This is called the 2-adic valuation or 2-adic order. \$\endgroup\$ – Paul Feb 13 '16 at 4:17
  • 7
    \$\begingroup\$ By the way, according to Wikipedia, the p-adic valuation of 0 is defined as infinity. \$\endgroup\$ – Paul Feb 13 '16 at 4:21
  • 3
    \$\begingroup\$ What an odd question! \$\endgroup\$ – corsiKa Feb 16 '16 at 17:58

62 Answers 62


Jelly, 4 bytes


In the latest version of Jelly, ÆEḢ (3 bytes) works.

Æf      Calculate the prime factorization. On negative input, -1 appended to the end.
  ċ2    Count the 2s.

Try it here.

  • \$\begingroup\$ This works for negative input too. \$\endgroup\$ – lirtosiast Feb 12 '16 at 16:36
  • 1
    \$\begingroup\$ @ThomasKwa I don't think that counts. Maybe a meta question? \$\endgroup\$ – orlp Feb 12 '16 at 16:50
  • \$\begingroup\$ Isn't ÆEḢ fine? It actually outputs 0 for odd numbers. \$\endgroup\$ – busukxuan Feb 13 '16 at 2:08
  • \$\begingroup\$ @busukxuan It doesn't work for ±1. \$\endgroup\$ – lirtosiast Feb 13 '16 at 2:10
  • 1
    \$\begingroup\$ @Tyzoid Jelly uses its own code page on the offline interpreter by default, in which one char is one byte. \$\endgroup\$ – lirtosiast Feb 16 '16 at 20:32

x86_64 machine code, 4 bytes

The BSF (bit scan forward) instruction does exactly this!

0x0f    0xbc    0xc7    0xc3

In gcc-style assembly, this is:

    .globl  f
    bsfl    %edi, %eax

The input is given in the EDI register and returned in the EAX register as per standard 64-bit calling conventions.

Because of two's complement binary encoding, this works for -ve as well as +ve numbers.

Also, despite the documentation saying "If the content of the source operand is 0, the content of the destination operand is undefined.", I find on my Ubuntu VM that the output of f(0) is 0.


  • Save the above as evenness.s and assemble with gcc -c evenness.s -o evenness.o
  • Save the following test driver as evenness-main.c and compile with gcc -c evenness-main.c -o evenness-main.o:
#include <stdio.h>

extern int f(int n);

int main (int argc, char **argv) {
    int i;

    int testcases[] = { 14, 20, 94208, 7, 0, -4 };

    for (i = 0; i < sizeof(testcases) / sizeof(testcases[0]); i++) {
        printf("%d, %d\n", testcases[i], f(testcases[i]));

    return 0;


  • Link: gcc evenness-main.o evenness.o -o evenness
  • Run: ./evenness

@FarazMasroor asked for more details on how this answer was derived.

I am more familiar with than the intricacies of x86 assembly, so typically I use a compiler to generate assembly code for me. I know from experience that gcc extensions such as __builtin_ffs(), __builtin_ctz() and __builtin_popcount() typically compile and assemble to 1 or 2 instructions on x86. So I started out with a function like:

int f(int n) {
    return __builtin_ctz(n);

Instead of using regular gcc compilation all the way to object code, you can use the -S option to compile just to assembly - gcc -S -c evenness.c. This gives an assembly file evenness.s like this:

    .file   "evenness.c"
    .globl  f
    .type   f, @function
    pushq   %rbp
    .cfi_def_cfa_offset 16
    .cfi_offset 6, -16
    movq    %rsp, %rbp
    .cfi_def_cfa_register 6
    movl    %edi, -4(%rbp)
    movl    -4(%rbp), %eax
    rep bsfl    %eax, %eax
    popq    %rbp
    .cfi_def_cfa 7, 8
    .size   f, .-f
    .ident  "GCC: (Ubuntu 4.8.4-2ubuntu1~14.04.1) 4.8.4"
    .section    .note.GNU-stack,"",@progbits

A lot of this can be golfed out. In particular we know that the calling convention for functions with int f(int n); signature is nice and simple - the input param is passed in the EDI register and the return value is returned in the EAX register. So we can take most of instructions out - a lot of them are concerned with saving registers and setting up a new stack frame. We don't use the stack here and only use the EAX register, so don't need to worry about other registers. This leaves "golfed" assembly code:

    .globl  f
    bsfl    %edi, %eax

Note as @zwol points out, you can also use optimized compilation to achieve a similar result. In particular -Os produces exactly the above instructions (with a few additional assembler directives that don't produce any extra object code.)

This is now assembled with gcc -c evenness.s -o evenness.o, which can then be linked into a test driver program as described above.

There are several ways to determine the machine code corresponding to this assembly. My favourite is to use the gdb disass disassembly command:

$ gdb ./evenness
GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.2) 7.7.1
Reading symbols from ./evenness...(no debugging symbols found)...done.
(gdb) disass /r f
Dump of assembler code for function f:
   0x00000000004005ae <+0>: 0f bc c7    bsf    %edi,%eax
   0x00000000004005b1 <+3>: c3  retq   
   0x00000000004005b2 <+4>: 66 2e 0f 1f 84 00 00 00 00 00   nopw   %cs:0x0(%rax,%rax,1)
   0x00000000004005bc <+14>:    0f 1f 40 00 nopl   0x0(%rax)
End of assembler dump.

So we can see that the machine code for the bsf instruction is 0f bc c7 and for ret is c3.

  • \$\begingroup\$ Do we not count this as 2? \$\endgroup\$ – lirtosiast Feb 12 '16 at 17:25
  • 2
    \$\begingroup\$ How do I learn Machine Language / Byte dump code? Can't find anything online \$\endgroup\$ – Faraz Masroor Feb 12 '16 at 23:17
  • 1
    \$\begingroup\$ This does not satisfy the C calling convention. On x86-32, the argument is passed on the stack; on x86-64, the argument is passed in %rdi. It only appears to work within your test harness because your compiler happens to have left a stale copy of the argument in %eax. It will break if you compile the harness evenness-main.c with different optimization settings; for me it breaks with -O, -O2, or -O3. \$\endgroup\$ – Anders Kaseorg Feb 13 '16 at 0:47
  • 1
    \$\begingroup\$ @AndersKaseorg - thanks for pointing that out. I've restricted it just to x86_64 now, so that input comes in RDI. \$\endgroup\$ – Digital Trauma Feb 13 '16 at 1:06
  • 3
    \$\begingroup\$ "Also, despite the documentation saying [...]" -- Any value you get necessarily agrees with the documentation. That doesn't rule out other processor models giving a different value than yours. \$\endgroup\$ – hvd Feb 15 '16 at 11:25

Python, 25 bytes

lambda n:len(bin(n&-n))-3

n & -n zeroes anything except the least significant bit, e.g. this:


We are interested in the number of trailing zeroes, so we convert it to a binary string using bin, which for the above number will be "0b10000". Since we don't care about the 0b, nor the 1, we subtract 3 from that strings length.

  • \$\begingroup\$ after posting my answer I figured yours was very smart, so I tried to convert it to Pyth and see if yours was shorter than mine. It yielded l.&Q_Q, using log2 instead of len(bin(_)). It was the same length as my Pyth answer as well as another Pyth answer, it seems this doesn't get shorter than 6 bytes in Pyth... \$\endgroup\$ – busukxuan Feb 12 '16 at 19:20

Pyth, 6 bytes


Try it here.

 P.aQ         In the prime factorization of the absolute value of the input
/    2        count the number of 2s.

JavaScript (ES6), 18 bytes


4 bytes shorter than 31-Math.clz32. Hah.

  • 1
    \$\begingroup\$ Oh wow, and I only recently learned about Math.clz32 too... \$\endgroup\$ – Neil Feb 13 '16 at 0:06
  • 1
    \$\begingroup\$ Damn I was going to post exactly this! +1 \$\endgroup\$ – Cyoce Feb 13 '16 at 19:25

JavaScript ES6, 22 19 bytes


Looks like recursion is the shortest route.

  • \$\begingroup\$ Oh nooo! You beat me! Nicely done :) +1 \$\endgroup\$ – Connor Bell Feb 12 '16 at 17:03

Pyth, 8 bytes

     Q    autoinitialized to eval(input())
   .B     convert to binary string
  c   \1  split on "1", returning an array of runs of 0s
 e        get the last run of 0s, or empty string if number ends with 1
l         take the length

For example, the binary representation of 94208 is:


After splitting on 1s and taking the last element of the resulting array, this becomes:


That's 12 zeroes, so it's "12-ly even."

This works because x / 2 is essentially x >> 1—that is, a bitshift right of 1. Therefore, a number is divisible by 2 only when the LSB is 0 (just like how a decimal number is divisible by 10 when its last digit is 0).


05AB1E, 4 5 bytes

Now supports negative numbers. Code:


Try it online!


Ä      # Abs(input)
 b     # Convert the number to binary
  1¡   # Split on 1's
    g  # Take the length of the last element

Uses CP-1252 encoding.


Pyth, 6 bytes


Basically just


MATL, 5 bytes


This works for all integers.

Try it online!

Yf      % implicit input. Compute (repeated) prime factors. For negative input
        % it computes the prime factors of the absolute value, except that for
        % -1 it produces an empty array instead of a single 1
2=s     % count occurrences of "2" in the array of prime factors
  • \$\begingroup\$ "And now, for something completely different..." \$\endgroup\$ – beaker Feb 12 '16 at 17:52

C, 36 (28) bytes

int f(int n){return n&1?0:f(n/2)+1;}

(Not testing for zero argument as a nonzero argument was specified.)

Update (in response to comment): If we allow K&R style function declarations, then we can have a 28-byte version:

f(n){return n&1?0:f(n/2)+1;}

In this case, we rely on the fact that the compiler defaults both n and the return type of f to int. This form generates a warning with C99 though and does not compile as valid C++ code.

  • \$\begingroup\$ If you change int n -> n it is still valid C code and cuts off 4 characters. \$\endgroup\$ – Josh Feb 12 '16 at 20:43
  • \$\begingroup\$ Good point. I was going to say that that triggers at least a warning with C99, but so does omitting the return type. And both trigger errors in C++. So I am changing my answer appropriately. \$\endgroup\$ – Viktor Toth Feb 12 '16 at 22:42

Java 7, 39 or maybe 44 bytes

int s(int a){return a%2!=0?0:s(a/2)+1;}

int s(int a){return a%2!=0|a==0?0:s(a/2)+1;}

Yay recursion! I had to use a != instead of a shorter comparison so it wouldn't overflow on negative input, but other than that it's pretty straightforward. If it's odd, send a zero. If even, add one and do it again.

There are two versions because right now output for zero is unknown. The first will recurse until the stack overflows, and output nothing, because 0 is infinitely even. The second spits out a nice, safe, but probably-not-mathematically-rigorous 0 for output.


JavaScript (ES6), 20 bytes 19 bytes.


This is a port of the Haskell solution by @nimi to JavaScript. It uses the "short-circuit" properties of && which returns its left side if it is falsey (which in this case is -0) or else returns its right side. To implement odd x = 0 we therefore make the left hand side 1 - (x % 2) which bubbles 0 through the &&, otherwise we recurse to 1 + f(x / 2).

The shaving of 1 - (x % 2) as (~x) % 2 is due to @Neil below, and has the strange property that causes the above function to emit -0 for small odd numbers. This value is a peculiarity of JS's decision that integers are IEEE754 doubles; this system has a separate +0 and -0 which are special-cased in JavaScript to be === to each other. The ~ operator computes the 32-bit-signed-integer bitwise inversion for the number, which for small odd numbers will be a negative even number. (The positive number Math.pow(2, 31) + 1 for example produces 0 rather than -0.) The strange restriction to the 32-bit-signed integers does not have any other effects; in particular it does not affect correctness.

  • \$\begingroup\$ ~x&1 is a byte shorter than 1-x%2. \$\endgroup\$ – Neil Feb 12 '16 at 21:54
  • \$\begingroup\$ @Neil Very cool. That has a somewhat counter-intuitive property but I'll take it anyway. \$\endgroup\$ – CR Drost Feb 12 '16 at 22:28

Perl 6, 23 18 bytes



> my &f = {+($_,*/2...^*%2)}
-> ;; $_? is raw { #`(Block|117104200) ... }
> f(14)
> f(20)
> f(94208)
> f(7)
> f(-4)

Ruby 24 bytes

My first code golf submission (yey!)


How I got here:

First I wanted to get code that actually fulfilled the spec to get my head around the problem, so I built the method without regards to number of bytes:

def how_even(x, times=1)
  half = x / 2
  if half.even?
    how_even(half, times+1)

with this knowledge I de-recursed the function into a while loop and added $* (ARGV) as the input and i as the count of how many times the number has been halved before it becomes odd.


I was quite proud of this and almost submitted it before it struck me that all this dividing by two sounded a bit binary to me, being a software engineer but not so much a computer scientist this wasn't the first thing that sprung to mind.

So I gathered some results about what the input values looked like in binary:

input      in binary      result
   14               1110   1
   20              10100   2
94208  10111000000000000  12

I noticed that the result was the number of positions to the left we have to traverse before the number becomes odd.

Doing some simple string manipulations I split the string on the last occurrence of 1 and counted the length of remaining 0s:


using ("%b" % x) formatting to turn a number to binary, and String#slice to slice up my string.

I have learnt a few things about ruby on this quest and look forward to more golfs soon!

  • 2
    \$\begingroup\$ Welcome to Programming Puzzles and Code Golf Stack Exchange. This is a great answer; I really like the explanation. +1! If you want more code-golf challenges, click on the code-golf tag. I look forward to seeing more of your answers. \$\endgroup\$ – wizzwizz4 Feb 14 '16 at 11:50
  • 1
    \$\begingroup\$ Feel free to ask me about any questions you have. Type @wizzwizz4 at the beginning of a comment to reply to me. (This works with all usernames!) \$\endgroup\$ – wizzwizz4 Feb 14 '16 at 11:53

J, 6 bytes



     |    absolute value
1&q:      exponent of 2 in the prime factorization

C, 37 bytes

f(int x){return x?x&1?0:1+f(x/2):0;} Recursively check the last bit until it's not a 0.

  • \$\begingroup\$ Also, there is f(int n){return __builtin_ctz(n);} if you're willing to use gcc extensions. Or even #define f __builtin_ctz \$\endgroup\$ – Digital Trauma Feb 12 '16 at 17:22
  • \$\begingroup\$ Remove int . It's implicit, just like the return type. \$\endgroup\$ – luser droog Feb 14 '16 at 4:01
  • \$\begingroup\$ @luserdroog, You mean f(n){...}? GCC won't compile it. I'm no C expert, but a quick search reveals that maybe this feature was removed in more recent versions of C. So maybe it will compile with the appropriate flags? \$\endgroup\$ – Andy Soffer Feb 14 '16 at 6:47
  • \$\begingroup\$ @AndySoffer I see. Maybe -ansi or -gnu99? I know I've gotten it to work. I wrote a tips answer about it! \$\endgroup\$ – luser droog Feb 14 '16 at 7:49

Haskell, 28 bytes

f x|odd x=0|1<2=1+f(div x 2)

Usage example: f 94208-> 12.

If the number is odd, the result is 0, else 1 plus a recursive call with half the number.

  • \$\begingroup\$ div x 2? Why not x/2? \$\endgroup\$ – CalculatorFeline May 8 '16 at 2:03
  • \$\begingroup\$ @CatsAreFluffy: Haskell has a very strict type system. div is integer division, / floating point division. \$\endgroup\$ – nimi May 8 '16 at 8:19

Befunge, 20


Code execution keeps moving to the right and wrapping around to the second character of the first line (thanks to the trailing #) until 2% outputs 1, which causes _ to switch the direction to left, then | to up, which wraps around to the < on the second row, which outputs and exits. We increment the second-to-the-top element of the stack every time through the loop, then divide the top by 2.


Retina, 29 17


Try it online!

2 bytes saved thanks to Martin!

Takes unary input. This repeatedly matches the largest amount of 1s it can such that that number of 1s matches exactly the rest of the 1s in the number. Each time it does this it prepends a ; to the string. At the end, we count the number of ;s in the string.

If you want decimal input, add:


to the beginning of the program.


Jolf, 6 bytes

Try it here!

Zl   2  count the number occurrences of 2 in
  m)j   the prime factorization of j (input)

Rather simple... Kudos to ETHProductions for ousting Jolf with the version that really should work!

  • 1
    \$\begingroup\$ 6 bytes seems to be the magic number for this challenge \$\endgroup\$ – Cyoce Feb 15 '16 at 7:44

PARI/GP, 17 bytes


6502 machine language, 7 bytes

To find the place value of the least significant 1 bit of the nonzero value in the accumulator, leaving the result in register X:

A2 FF E8 4A 90 FC 60

To run this on the 6502 simulator on e-tradition.net, prefix it with A9 followed by an 8-bit integer.

This disassembles to the following:

    ldx #$FF
    lsr a     ; set carry to 0 iff A divisible by 2, then divide by 2 rounding down
    bcc loop  ; keep looping if A was divisible by 2
    rts       ; return with result in X

This is equivalent to the following C, except that C requires int to be at least 16-bit:

unsigned int count_trailing_zeroes(int signed_a) {
    unsigned int carry;
    unsigned int a = signed_a;  // cast to unsigned makes shift well-defined
    unsigned int x = UINT_MAX;
    do {
        x += 1;
        carry = a & 1;
        a >>= 1;
    } while (carry == 0);
    return x;

The same works on a 65816, assuming MX = 01 (16-bit accumulator, 8-bit index), and is equivalent to the above C snippet.


Brachylog, 27 15 bytes



$pA             § Unify A with the list of prime factors of the input
   :2x          § Remove all occurences of 2 in A
      lL,       § L is the length of A minus all the 2s
         Al-L=. § Unify the output with the length of A minus L

CJam, 8 bytes


Read integer, absolute value, prime factorize, count twos.


JavaScript ES6, 36 38 bytes

Golfed two bytes thanks to @ETHproductions

Fairly boring answer, but it does the job. May actually be too similar to another answer, if he adds the suggested changes then I will remove mine.


To run, assign it to a variable (a=>{for...) as it's an anonymous function, then call it with a(100).

  • \$\begingroup\$ Nice answer! b%2==0 can be changed to b%2-1, and c++ can be moved inside the last part of the for statement. I think this would also work: b=>eval("for(c=0;b%2-1;b/=2)++c") \$\endgroup\$ – ETHproductions Feb 12 '16 at 16:37
  • \$\begingroup\$ @ETHproductions So it can! Nice catch :) \$\endgroup\$ – Connor Bell Feb 12 '16 at 16:44
  • \$\begingroup\$ One more byte: b%2-1 => ~b&1 Also, I think this fails on input of 0, which can be fixed with b&&~b&1 \$\endgroup\$ – ETHproductions Feb 12 '16 at 18:04
  • \$\begingroup\$ Froze my computer testing this on a negative number. b%2-1 check fails for negative odd numbers. \$\endgroup\$ – Patrick Roberts Feb 12 '16 at 23:23

ES6, 22 bytes


Returns -1 if you pass 0.

  • \$\begingroup\$ Ah, nice. I forgot about clz32 :P \$\endgroup\$ – Conor O'Brien Feb 12 '16 at 22:10

DUP, 20 bytes


Try it here!

Converted to recursion, output is now the top number on stack. Usage:



[                ]f: {save lambda to f}
 2/\0=               {top of stack /2, check if remainder is 0}
      [     ][ ]?    {conditional}
       f;!1+         {if so, then do f(top of stack)+1}
              0      {otherwise, push 0}

Japt, 9 5 bytes

¢w b1

Test it online!

The previous version should have been five bytes, but this one actually works.

How it works

       // Implicit: U = input integer
¢      // Take the binary representation of U.
w      // Reverse.
b1     // Find the first index of a "1" in this string.
       // Implicit output

C, 44 40 38 36 bytes

2 bytes off thanks @JohnWHSmith. 2 bytes off thanks @luserdroog.

a;f(n){for(;~n&1;n/=2)a++;return a;}

Test live on ideone.

  • \$\begingroup\$ You might be able to take 1 byte off by replacing the costly !(n%2) with a nice little ~n&1. \$\endgroup\$ – John WH Smith Feb 12 '16 at 18:24
  • \$\begingroup\$ @JohnWHSmith. That was nice!! Thanks \$\endgroup\$ – removed Feb 12 '16 at 19:01
  • \$\begingroup\$ Remove the =0. Globals are implicitly initialized to 0. \$\endgroup\$ – luser droog Feb 14 '16 at 3:59
  • \$\begingroup\$ @luserdroog. Thanks, I didn't know about that. \$\endgroup\$ – removed Feb 14 '16 at 11:01
  • \$\begingroup\$ Correct me if I'm wrong but since this function uses the global variable a, isn't it only guaranteed to work the first time it's called? I didn't know that was allowed. \$\endgroup\$ – Patrick Roberts Oct 27 '16 at 1:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.