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

1 2

SmileBASIC, 45 bytes

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

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


Pure bash, 37 bytes

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

A recursive solution.

1 2

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.