How even is a number?

47

8

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.

Gust van de Wal

Posted 2016-02-12T15:54:09.577

Reputation: 630

11@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 ;) – Geobits – 2016-02-12T16:43:39.333

I'm voting to close for now until clarification is added. The answers have varying outputs, and that's not helpful to the site. – Geobits – 2016-02-12T17:20:47.380

@AlexL. I guess it would best be indefinite, though I'm not a mathematician. – busukxuan – 2016-02-12T19:37:15.457

1The input will be a nonzero integer Does this need to be edited following your comment about zero being a potential input? – trichoplax – 2016-02-13T01:55:35.657

2This is called the 2-adic valuation or 2-adic order. – Paul – 2016-02-13T04:17:00.897

7By the way, according to Wikipedia, the p-adic valuation of 0 is defined as infinity. – Paul – 2016-02-13T04:21:10.853

@Paul I call it the lowest set bit. Thanks for your info. – John Dvorak – 2016-02-13T10:44:45.373

1@Paul think it's okay if my submission evaluates its 2-adic order as -Infinity according to Math.log2(0)? – Patrick Roberts – 2016-02-13T21:47:52.870

This is the "find first set" or "count trailing zeroes" function, right?

– Damian Yerrick – 2016-02-14T20:52:43.523

3What an odd question! – corsiKa – 2016-02-16T17:58:37.557

Answers

23

Jelly, 4 bytes

Æfċ2

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.

lirtosiast

Posted 2016-02-12T15:54:09.577

Reputation: 20 331

This works for negative input too. – lirtosiast – 2016-02-12T16:36:47.373

1@ThomasKwa I don't think that counts. Maybe a meta question? – orlp – 2016-02-12T16:50:11.133

Isn't ÆEḢ fine? It actually outputs 0 for odd numbers. – busukxuan – 2016-02-13T02:08:49.647

@busukxuan It doesn't work for ±1. – lirtosiast – 2016-02-13T02:10:22.197

@ThomasKwa Odd, it seems to be working in my browser. – busukxuan – 2016-02-13T02:15:07.947

@busukxuan Hmm, I think Dennis must have just pushed it. – lirtosiast – 2016-02-13T02:24:17.823

Looks like 6 bytes to me: c3 86 45 e1 b8 a2 – Tyzoid – 2016-02-16T20:29:58.327

1

@Tyzoid Jelly uses its own code page on the offline interpreter by default, in which one char is one byte.

– lirtosiast – 2016-02-16T20:32:18.277

In modern Jelly, this is a built-in: ȯ2 – Lynn – 2016-09-18T13:07:05.003

93

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
f:
    bsfl    %edi, %eax
    ret

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.

Instructions:

  • 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;
}

Then:

  • 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"
    .text
    .globl  f
    .type   f, @function
f:
.LFB0:
    .cfi_startproc
    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
    ret
    .cfi_endproc
.LFE0:
    .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
f:
    bsfl    %edi, %eax
    ret

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.
(gdb) 

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

Digital Trauma

Posted 2016-02-12T15:54:09.577

Reputation: 64 644

Do we not count this as 2? – lirtosiast – 2016-02-12T17:25:37.450

@ThomasKwa I suppose that could be argued. I don't think that could be used as a complete function or program that the question is asking for though. I've not done a machine code-only answer before, but my feeling is that should always be at least a ret instruction at the end so that it is usable – Digital Trauma – 2016-02-12T19:18:57.787

2How do I learn Machine Language / Byte dump code? Can't find anything online – Faraz Masroor – 2016-02-12T23:17:58.923

1This 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. – Anders Kaseorg – 2016-02-13T00:47:37.553

1@AndersKaseorg - thanks for pointing that out. I've restricted it just to x86_64 now, so that input comes in RDI. – Digital Trauma – 2016-02-13T01:06:01.667

@AndersKaseorg what if I specify regcall? – John Dvorak – 2016-02-13T10:46:52.300

You could have had the compiler "golf" the assembly language for you by turning on optimization ;-) – zwol – 2016-02-13T17:50:30.643

@FarazMasroor read the manual.

– rightfold – 2016-02-14T22:41:39.540

3"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. – hvd – 2016-02-15T11:25:25.300

@zwol yes -Os produces exactly the right instructions. – Digital Trauma – 2016-02-17T23:47:33.727

0F BC C7 C3 is a better way to show the hex dump. – dkudriavtsev – 2016-08-08T20:42:50.313

25

Python, 25 bytes

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

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

100010101010100000101010000
            v
000000000000000000000010000

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.

orlp

Posted 2016-02-12T15:54:09.577

Reputation: 37 067

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... – busukxuan – 2016-02-12T19:20:43.707

21

Pyth, 6 bytes

/P.aQ2

Try it here.

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

lirtosiast

Posted 2016-02-12T15:54:09.577

Reputation: 20 331

15

JavaScript (ES6), 18 bytes

n=>Math.log2(n&-n)

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

Patrick Roberts

Posted 2016-02-12T15:54:09.577

Reputation: 2 475

1Oh wow, and I only recently learned about Math.clz32 too... – Neil – 2016-02-13T00:06:30.390

1Damn I was going to post exactly this! +1 – Cyoce – 2016-02-13T19:25:50.980

13

JavaScript ES6, 22 19 bytes

f=x=>x%2?0:f(x/2)+1

Looks like recursion is the shortest route.

ETHproductions

Posted 2016-02-12T15:54:09.577

Reputation: 47 880

Oh nooo! You beat me! Nicely done :) +1 – Connor Bell – 2016-02-12T17:03:33.377

6

Pyth, 8 bytes

lec.BQ\1
     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:

10111000000000000

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

000000000000

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).

Doorknob

Posted 2016-02-12T15:54:09.577

Reputation: 68 138

6

05AB1E, 4 5 bytes

Now supports negative numbers. Code:

Äb1¡g

Try it online!

Explanation:

Ä      # 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.

Adnan

Posted 2016-02-12T15:54:09.577

Reputation: 41 965

6

MATL, 5 bytes

Yf2=s

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

Luis Mendo

Posted 2016-02-12T15:54:09.577

Reputation: 87 464

"And now, for something completely different..." – beaker – 2016-02-12T17:52:40.933

6

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.

Viktor Toth

Posted 2016-02-12T15:54:09.577

Reputation: 161

If you change int n -> n it is still valid C code and cuts off 4 characters. – Josh – 2016-02-12T20:43:11.613

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. – Viktor Toth – 2016-02-12T22:42:03.817

6

Pyth, 6 bytes

x_.BQ1

Basically just

convert2BinString(evaluatedInput())[::-1].index("1")

busukxuan

Posted 2016-02-12T15:54:09.577

Reputation: 2 728

5

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.

Geobits

Posted 2016-02-12T15:54:09.577

Reputation: 19 061

4

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.

Andy Soffer

Posted 2016-02-12T15:54:09.577

Reputation: 141

Also, there is f(int n){return __builtin_ctz(n);} if you're willing to use gcc extensions. Or even #define f __builtin_ctz – Digital Trauma – 2016-02-12T17:22:12.243

Remove int. It's implicit, just like the return type. – luser droog – 2016-02-14T04:01:01.630

@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? – Andy Soffer – 2016-02-14T06:47:19.940

@AndySoffer I see. Maybe -ansi or -gnu99? I know I've gotten it to work. I wrote a tips answer about it! – luser droog – 2016-02-14T07:49:25.523

4

JavaScript (ES6), 20 bytes 19 bytes.

f=x=>~x%2&&1+f(x/2)

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.

CR Drost

Posted 2016-02-12T15:54:09.577

Reputation: 949

~x&1 is a byte shorter than 1-x%2. – Neil – 2016-02-12T21:54:56.160

@Neil Very cool. That has a somewhat counter-intuitive property but I'll take it anyway. – CR Drost – 2016-02-12T22:28:05.637

4

Perl 6, 23 18 bytes

{+($_,*/2...^*%2)}

usage

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

Hotkeys

Posted 2016-02-12T15:54:09.577

Reputation: 1 015

4

Ruby 24 bytes

My first code golf submission (yey!)

("%b"%$*[0])[/0*$/].size

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)
  else
    times
  end
end

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.

x=$*[0];i=1;while(x=x/2)%2<1;i+=1;end;i

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:

("%b"%$*[0])[/0*$/].size

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!

ryantk

Posted 2016-02-12T15:54:09.577

Reputation: 101

2Welcome 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 [tag:code-golf] tag. I look forward to seeing more of your answers. – wizzwizz4 – 2016-02-14T11:50:19.810

1Feel 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!) – wizzwizz4 – 2016-02-14T11:53:15.253

4

J, 6 bytes

1&q:@|

Explanation:

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

alephalpha

Posted 2016-02-12T15:54:09.577

Reputation: 23 988

3

Retina, 29 17

+`\b(1+)\1$
;$1
;

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:

\d+
$0$*1

to the beginning of the program.

FryAmTheEggman

Posted 2016-02-12T15:54:09.577

Reputation: 16 206

3

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.

nimi

Posted 2016-02-12T15:54:09.577

Reputation: 34 639

div x 2? Why not x/2? – CalculatorFeline – 2016-05-08T02:03:08.580

@CatsAreFluffy: Haskell has a very strict type system. div is integer division, / floating point division. – nimi – 2016-05-08T08:19:20.880

3

Befunge, 20

&:2%#|_\1+\2/#
   @.<

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.

histocrat

Posted 2016-02-12T15:54:09.577

Reputation: 20 600

3

Jolf, 6 bytes

Try it here!

Zlm)j2
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!

Conor O'Brien

Posted 2016-02-12T15:54:09.577

Reputation: 36 228

16 bytes seems to be the magic number for this challenge – Cyoce – 2016-02-15T07:44:19.717

3

PARI/GP, 17 bytes

n->valuation(n,2)

Charles

Posted 2016-02-12T15:54:09.577

Reputation: 2 435

3

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:

count_trailing_zeroes:
    ldx #$FF
loop:
    inx
    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.

Damian Yerrick

Posted 2016-02-12T15:54:09.577

Reputation: 163

2

Brachylog, 27 15 bytes

$pA:2xlL,Al-L=.

Explanation

$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

Fatalize

Posted 2016-02-12T15:54:09.577

Reputation: 32 976

2

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.

removed

Posted 2016-02-12T15:54:09.577

Reputation: 2 785

You might be able to take 1 byte off by replacing the costly !(n%2) with a nice little ~n&1. – John WH Smith – 2016-02-12T18:24:33.020

@JohnWHSmith. That was nice!! Thanks – removed – 2016-02-12T19:01:32.763

Remove the =0. Globals are implicitly initialized to 0. – luser droog – 2016-02-14T03:59:12.150

@luserdroog. Thanks, I didn't know about that. – removed – 2016-02-14T11:01:28.847

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. – Patrick Roberts – 2016-10-27T01:45:30.320

2

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.

b=>{for(c=0;b%2-1;c++)b/=2;alert(c)}

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

Connor Bell

Posted 2016-02-12T15:54:09.577

Reputation: 81

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") – ETHproductions – 2016-02-12T16:37:36.650

@ETHproductions So it can! Nice catch :) – Connor Bell – 2016-02-12T16:44:47.867

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 – ETHproductions – 2016-02-12T18:04:33.657

Froze my computer testing this on a negative number. b%2-1 check fails for negative odd numbers. – Patrick Roberts – 2016-02-12T23:23:20.703

2

CJam, 8 bytes

rizmf2e=

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

Lynn

Posted 2016-02-12T15:54:09.577

Reputation: 55 648

2

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

ETHproductions

Posted 2016-02-12T15:54:09.577

Reputation: 47 880

2

ES6, 22 bytes

n=>31-Math.clz32(n&-n)

Returns -1 if you pass 0.

Neil

Posted 2016-02-12T15:54:09.577

Reputation: 95 035

Ah, nice. I forgot about clz32 :P – Conor O'Brien – 2016-02-12T22:10:51.030

2

DUP, 20 bytes

[$2/%0=[2/f;!1+.][0]?]f:

Try it here!

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

94208[2/\0=[f;!1+][0]?]f:f;!

Explanation

[                ]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}

Mama Fun Roll

Posted 2016-02-12T15:54:09.577

Reputation: 7 234

2

, 8 chars / 10 bytes

ïⓑᴙą1

Try it here (Firefox only).

Explanation

Converts input to binary, reverses it, then gets index of first 1.

Mama Fun Roll

Posted 2016-02-12T15:54:09.577

Reputation: 7 234

2

Oracle SQL 11.2, 111 bytes

WITH v(i)AS(SELECT 1 FROM DUAL UNION ALL SELECT i+1 FROM v WHERE MOD(:1/POWER(2,i),1)=0)SELECT MAX(i)-1 FROM v;

Un-golfed

WITH v(i) AS 
(
  SELECT 1 FROM DUAL 
  UNION ALL 
  SELECT i+1 FROM v WHERE MOD(:1/POWER(2,i),1)=0
)
SELECT MAX(i)-1 FROM v;

Jeto

Posted 2016-02-12T15:54:09.577

Reputation: 1 601

2

Javascript ES6, 39 chars

n=>n.toString(2).match(/0*$/)[0].length

Test:

[14,20,94208,7,-4].map(n=>n.toString(2).match(/0*$/)[0].length) == "1,2,12,0,2"

Qwertiy

Posted 2016-02-12T15:54:09.577

Reputation: 2 697

2

Python, 48 chars

print len(str(bin(int(input()))).split("1")[-1])

Simply counts the number of 0s at the end of the binary number

Dave Lin

Posted 2016-02-12T15:54:09.577

Reputation: 71

1

Excel, 20 bytes

Works up to 2^53 (9,007,199,254,740,990)

=LOG(GCD(A1,2^53),2)

Using Binarys, a 36 byte solution that only works up to 511:

=10-FIND(2,DEC2BIN(A2)+DEC2BIN(-A2))

Wernisch

Posted 2016-02-12T15:54:09.577

Reputation: 2 534

1

PowerShell, 36 bytes

param($a)for(;!($a%2)){$a/=2;$o++}$o

Takes input $a, then enters a for() loop. There is no setup, but the conditional means the loop ends when $a is no longer even. Inside the loop, we just divide $a by 2 and increment a counter, then output the counter.

The above correctly accounts for negative numbers (in PowerShell, the % operator follows the sign of the dividend, but any non-zero number is truthy, the ! of which is falsey).

AdmBorkBork

Posted 2016-02-12T15:54:09.577

Reputation: 41 581

1

Javascript, 45 39 38 bytes

1 byte off thanks @manatwork.

i=>/0*$/.exec(i.toString(2))[0].length

f=
i=>/0*$/.exec(i.toString(2))[0].length

F=i=>document.body.innerHTML+='<pre>f('+i+') -> '+f(i)+'\n</pre>'

F(14)
F(20)
F(94208)

removed

Posted 2016-02-12T15:54:09.577

Reputation: 2 785

.exec() is 1 character shorter, just have to reverse it: /0*$/.exec(i.toString(2)). – manatwork – 2016-02-12T17:15:15.717

@manatwork. Good one, thanks! – removed – 2016-02-12T17:23:48.133

1

Java, 44 39 bytes

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

Works for odd, zero, and negative numbers.

Golfed 5 bytes because input will not be zero.

HyperNeutrino

Posted 2016-02-12T15:54:09.577

Reputation: 26 575

FYI, this is almost exactly like mine: http://codegolf.stackexchange.com/a/71853/14215

– Geobits – 2016-02-12T16:45:06.297

works for zero But we don't know what to do for zero. – Dennis – 2016-02-12T16:45:38.530

@Geobits Shoot. I didn't see yours earlier! I was looking for a Java solution, but I must have skipped over it. Sorry. – HyperNeutrino – 2016-02-12T16:45:54.390

@Dennis Good point. What I mean is that it will not crash, throw errors, or go into an indefinite loop. – HyperNeutrino – 2016-02-12T16:46:14.623

Lol 44 with strikethrough looks almost exactly the same ;) – HyperNeutrino – 2016-02-12T23:07:25.670

1

Seriously, 9 bytes

,wii2=*.

Contains an unprintable (0x7F) at the end. Hexdump:

2c77 6969 323d 2a2e 7f

Try it online!

Explanation:

,wii2=*.<0x7F>
,w              get prime factorization of input (list of base, exp pairs)
  ii            flatten first (base, exp) pair so that base, exp is top of stack
    2=*         multiply exponent by 1 if base is 2 else 0
       .<0x7F>  print top item and exit

Mego

Posted 2016-02-12T15:54:09.577

Reputation: 32 998

1

Perl 6  28  27 bytes

{($_+&-$_).polymod(2 xx*)-1}
{($_+&-$_).base(2).chars-1}

Usage:

my &code = {($_+&-$_).base(2).chars-1}

say code    14; # 1
say code    20; # 2
say code 94208; # 12
say code     7; # 0
say code    -4; # 2

Brad Gilbert b2gills

Posted 2016-02-12T15:54:09.577

Reputation: 12 713

1

TeaScript, 14 9 bytes

xT2)r1)i1

Ungolfed:

xT2)       // take input and convert to base 2
    r1)    // reverse the string
       i1  // get the index of '1'

You can try it here

Gust van de Wal

Posted 2016-02-12T15:54:09.577

Reputation: 630

1You can use v instead of r1) to reverse the string. You also don't need the x at the beginning as it's implicitly inserted – Downgoat – 2016-02-14T20:27:30.557

1

Mathematica, 20 bytes

#~IntegerExponent~2&

Yet another long, un-golfable built-in...

LegionMammal978

Posted 2016-02-12T15:54:09.577

Reputation: 15 731

1

R, 30 bytes

sum(gmp::factorize(scan())==2)

Assumes gmp package installed

mnel

Posted 2016-02-12T15:54:09.577

Reputation: 826

1

PHP, 36 28 bytes

Used a different approach than most others. I'm checking divisibility by 2^N where I'm increasing N until it's no longer divisible by it.

for(;0==$argv[1]%2**++$b;);echo$b-1;

Run like this (-d added for aesthetics only):

php -d error_reporting=32757 -r 'for(;0==$argv[1]%2**++$b;);echo$b-1; echo"\n";' -- -65536

Implementing orlp's log algorithm would be even shorter. I don't like the requirement to create a file for PHP golfs, but this would be the shortest:

<?=log(($x=$argv[1])&-$x,2);

Edit: I found out you can actually run that without creating a file, by piping it like this:

echo '<?=log(($x=$argv[1])&-$x,2);' | php -- -65536

aross

Posted 2016-02-12T15:54:09.577

Reputation: 1 583

1

POSIX shell and GNU/BSD utilities, 43 30 bytes

factor ${1#-}|rs -T|grep -xc 2

We simply count the number of 2s in the output of the factor command.

Toby Speight

Posted 2016-02-12T15:54:09.577

Reputation: 5 058

1

Pure Bash, 40

If 0 could not be submited as input... Thanks to @TobySpeight for help me to drop a lot.

for((o=0;1<<o&~i;++o));do :;done;echo $o

Proof

pureBashStr='for((o=0;1<<o&~i;o++));do :;done;echo $o'
echo ${#pureBashStr}
40

for i in 14 20 64#w0000 94208 7 -4 ;do
    printf " %8s: %4d\n" $i $(
        eval $pureBashStr)
  done
       14:    1
       20:    2
 64#w0000:   29
    94208:   12
        7:    0
       -4:    2

+10 to support 0 case: 50

pureBashStr='for((o=0;1<<o&~i;o++));do((i))||break;done;echo $o'
i=0
printf " %8s: %4d\n" $i $(eval $pureBashStr)
        0:    0

F. Hauri

Posted 2016-02-12T15:54:09.577

Reputation: 2 654

i cannot be zero, according to the question. I think you can simplify the test to o=0;until((1<<o&i));do((++o));done;echo $o for 43 bytes. – Toby Speight – 2016-02-16T17:17:26.000

Or even for((o=0;1<<o&~i;++o));do :;done;echo $o for 41. – Toby Speight – 2016-02-16T17:29:52.260

1

Groovy, 83 bytes

There was not a groovy answer yet, so here goes. Definitely room for improvement.

int n=args[0].toInteger();def e(int n){x=0;while(n%2==0){n/=2;x++;};print x;};e(n);

You can use it with: groovy filename.groovy "94208"

Xgongiveittoya

Posted 2016-02-12T15:54:09.577

Reputation: 111

1

Python 2, 27 bytes

e=lambda n:~n%2and e(n/2)+1

In Python 3, you'd have to use e(n//2), since ~ operator doesn't work with floats.

pafcjo

Posted 2016-02-12T15:54:09.577

Reputation: 31

Try ~n-2and-~e(n-2) – CalculatorFeline – 2016-05-08T02:08:54.943

1

R, 56 46 40 bytes

x=scan();a=0;while(!x%%2){x=x/2;a=a+1};a

Another answer than @mnel's one without the gmp package.

Thanks to @user5957401 for saving 10 bytes

Thanks to @Frédéric for saving 6 bytes

Mamie

Posted 2016-02-12T15:54:09.577

Reputation: 171

you could shorten your while condition. while(!x%%2) should do the trick. – user5957401 – 2016-08-08T20:31:23.517

Since OP's asking for either a program or a function, you could golf some bytes by taking x as a scan : x=scan();a=0;... – Frédéric – 2016-08-11T11:24:02.213

0

SmileBASIC, 45 bytes

INPUT N@L
IF!(N<<31)THEN N=N>>1Q=Q+!GOTO@L
?Q

I'm pretty sure N<<31 is the shortest way to check the lowest bit in SB, since ​ MOD ​ and ​ AND ​ are so long.

12Me21

Posted 2016-02-12T15:54:09.577

Reputation: 6 110

0

Pure bash, 37 bytes

(($1%2))&&echo 0||echo $[1+`$0 $1/2`]

A recursive solution.

Mitchell Spector

Posted 2016-02-12T15:54:09.577

Reputation: 3 392

0

Pylons, 22 bytes.

:Ai0?Aw[A2A/]1+,2A%1g}

Man, this turned out a lot longer than I thought it would.

Turns out it broke on 0 input, so I fixed it.

How it works:

:Ai     # Set A equal to command line input.
0       # Push 0 to the stack.
?A      # Check if A is equal to the top of the stack, if so, skip the next instrutction. In this case, the while loop.
w       # Start a while loop.
 [A2A/] # Set A equal to A / 2.
 1+     # Push 1 to the stack and add it to the number at the top of the stack.
 ,      # Switch to loop iteration.
 2A%    # Push A%2 to the loop condition stack.
    1g  # Check if 1 is greater than the top of the loop condition stack. 
      } # End the while loop
        # Print the stack at the end of the instruction set.

Morgan Thrapp

Posted 2016-02-12T15:54:09.577

Reputation: 3 574

0

jq, 26 characters

[while(.%2==0;./2)]|length

Sample run:

bash-4.3$ jq '[while(.%2==0;./2)]|length' <<< 94208
12

bash-4.3$ jq '[while(.%2==0;./2)]|length' <<< -4
2

On-line test:

manatwork

Posted 2016-02-12T15:54:09.577

Reputation: 17 865

0

PHP, 40 bytes

function e($i){return $i%2?0:e($i/2)+1;}

Nuno Pereira

Posted 2016-02-12T15:54:09.577

Reputation: 101

Thank you for the syntax highlighting edit, @rink.atendant.6 – Nuno Pereira – 2016-02-14T15:10:04.153

0

Whitespace, 109 bytes

Unfortunately I can't put the code here because it gets recognized as formating so this will have to do. http://pastebin.com/cmH30iUF

Try it here: http://ws2js.luilak.net/interpreter.html Just paste the code, type a number, and hit enter.

18107

Posted 2016-02-12T15:54:09.577

Reputation: 101

Another option is to use STL for the code here, since link-only answers are discouraged. Here's an example.

– Geobits – 2016-02-16T14:47:50.483

0

MS SQL, 81 bytes

For funsies. convert( varbinary() ) end up taking more space than the modulo loop.

create proc p @n int as declare @i int=0while @n%2=0 select @i+=1,@n=@n/2print @i

Test with

p 14;
go
p 20;
go
p 94208;
go
p 7;
go
p -4;
go

Peter Vandivier

Posted 2016-02-12T15:54:09.577

Reputation: 211

0

dc, 21 bytes

#!/usr/bin/dc
?[dd2/r2%0=f]dsfxz2-p

Reads the input, then successively divides by 2, building a stack as we go. When we get to an odd number, count the stack depth, adjusting for the odd number and its duplicate.

Toby Speight

Posted 2016-02-12T15:54:09.577

Reputation: 5 058

0

Perl 5, 26 bytes

25, plus 1 for -pe instead of -e.

$i++,$_/=2until$_%2;$_=$i

or

$_=sprintf'%b',$_;s/.*1//

(The latter has output in unary.)

msh210

Posted 2016-02-12T15:54:09.577

Reputation: 3 094

0

Turing Machine, 53 char

   B    1   i

0  B4L  i1R 

1  B2L  11R 

2       B3L B7L

3           10R

4  B5L  

5  16R  

6  B0R  16R 

7  Bh   B7L 

*       1*L

It accepts as an input a string of ones and outputs a string of ones. It repeatedly divides the number by 2 and adds 1 to the count after every halving. Try it out here.

Random

Posted 2016-02-12T15:54:09.577

Reputation: 1

0

Scala 42 bytes

def e(n:Int):Int=if(n%2==0)e(n/2)+1 else 0

Similar to Java, but 2 bytes smaller.

Leonardo Otto

Posted 2016-02-12T15:54:09.577

Reputation: 101

0

Microscript II, 28 27 bytes

0s<N[sv2sl%!(.5*v>1+s<l)]>o

There's probably still room for improvement here.

SuperJedi224

Posted 2016-02-12T15:54:09.577

Reputation: 11 342

0

R, 37 bytes

f=function(n)ifelse(n%%2,0,1+f(n/2))
or
f=function(n)if(n%%2)0 else 1+f(n/2)

Checks if the current number is divisible by two. If not, returns 0, if it is, divides and recursively calls itself again while setting up a counter to add 1.

user5957401

Posted 2016-02-12T15:54:09.577

Reputation: 699