47
\$\begingroup\$

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.

\$\endgroup\$
  • 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

0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

Pure bash, 37 bytes

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

A recursive solution.

\$\endgroup\$

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.