47
\$\begingroup\$

Task

Given \$n\$, output position of the last odd digit in the decimal representation of \$2^n\$ (counting from the end).

Rules

  • There are no odd digits for \$n=1,2,3,6,11\$ \$(2, 4, 8, 64, 2048)\$ - you may output anything that is not a positive integer for them (no need to be consistent).
  • You choose whether to handle \$n=0\$.
  • Standard I/O rules.
  • This is .

Test-cases

    n answer   (2^n)
    1     NA       2
    2     NA       4
    3     NA       8
    4      2      16
    5      2      32
    6     NA      64
    7      3     128
    8      2     256
    9      2     512
   10      4    1024
   11     NA    2048
   12      2    4096
   13      2    8192
   14      3   16384
   15      3   32768
   16      2   65536
   17      2  131072
   18      3  262144
   19      6  524288
   20      2 1048576

Inspired by this Mathematics SE post and comments on OEIS A068994.

\$\endgroup\$
11
  • 7
    \$\begingroup\$ 14 answers and 7 votes... Imho you don’t have to vote for everything, but if you answer... \$\endgroup\$
    – lesobrod
    Jun 16 at 14:02
  • 2
    \$\begingroup\$ @lesobrod - I have no hard feelings towards the community here. Simple challenges like this one very often attract many answers and don't tend to gather many upvotes. \$\endgroup\$
    – pajonk
    Jun 16 at 14:21
  • 11
    \$\begingroup\$ @lesobrod That's one of my pet peeves here. How can a challenge be worth answering but not worth upvoting? \$\endgroup\$
    – Luis Mendo
    Jun 16 at 14:39
  • 3
    \$\begingroup\$ Could we get clarity on what "you may output anything that is not a positive integer for them" means? May we error rather than output? May we never halt? \$\endgroup\$ Jun 16 at 16:35
  • 3
    \$\begingroup\$ @JonathanAllan I'll allow erroring, but I'd like solutions to terminate (best reference I could find on Meta). Counting may start from 0 - for me that's covered in standard sequence I/O rules. \$\endgroup\$
    – pajonk
    Jun 16 at 18:08

38 Answers 38

8
\$\begingroup\$

JavaScript (ES7), 35 bytes

Returns NaN if there's no odd digit. Supports \$n=0\$.

n=>(g=k=>k?k&1||1+g(k/10):+g)(2**n)

Try it online!

Commented

n => (        // n = input
  g = k =>    // g = recursive function looking for an odd digit in k
  k ?         // if k is not zero:
    k & 1 ||  //   stop and return 1 if the least significant bit is set
    1 +       //   otherwise, increment the final result
    g(k / 10) //   and do a recursive call with k / 10
              //   note that we rely on arithmetic underflow to stop the
              //   recursion if the LSB is never set
  :           // else:
    +g        //   no odd digit found: return NaN, which will propagate
              //   all the way to the initial call
)(2 ** n)     // initial call to g with k = 2 ** n

JavaScript (ES7), 30 bytes

A simpler version that throws an error if there's no odd digit.

n=>(g=k=>k&1||1+g(k/10))(2**n)

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ I guess '111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111k=>k?k&1||1+g(k/10):g' is also not an integer and valid as didn't find output \$\endgroup\$
    – l4m2
    Jul 1 at 14:54
8
\$\begingroup\$

Excel, 50 bytes

=XMATCH(1,MOD(MID(2^A1,1+LEN(2^A1)-ROW(A:A),1),2))

Input in cell A1. Outputs an #N/A error if no odd digit exists.

Edit: JvdV's wonderfully creative use of passing an array to TEXTBEFORE means that we can employ alternatives such as:

=1+LEN(TEXTAFTER(2^A1,{1,3,5,7,9},-1))

for just 38 bytes.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Nice! I've just stumbled across this post and puzzled a bit. For 47 bytes (and probably a substantial speed increasement) you could try: =LEN(2^A1)-LEN(TEXTBEFORE(2^A1,{1,3,5,7,9},-1)) which would still output #N/A if not applicable. \$\endgroup\$
    – JvdV
    Jun 20 at 14:45
  • 1
    \$\begingroup\$ @JvdV Fantastic use of TEXTBEFORE! That's significantly different from my solution, so suggest you post it as a separate answer. Looking into it, could you also use =1+LEN(TEXTAFTER(2^A1,{1,3,5,7,9},-1)) for just 38 bytes? \$\endgroup\$ Jun 20 at 19:32
  • \$\begingroup\$ Yes that should work because there should always be an even number at the end of the 2^n. Therefore TEXTAFTER() should correctly parse an error if no odd number is present. Please, I don't want to intervene with your answer but I insist on you just adding this into your current post for future reference. Perfectly fine with me! \$\endgroup\$
    – JvdV
    Jun 20 at 21:02
8
\$\begingroup\$

Ruby, 31 bytes

->n{(2**n).digits.index &:odd?}

0-indexed; no result returns nil.

I've been programming Ruby for about a year, and really enjoying it. As this example shows, it's possible to be concise and human readable.

->n{ ... } is the syntax for creating a lambda. It's not super elegant, but most of the time you're writing methods and not lambdas in Ruby anyways.

.digits already returns an array of digits starting with the least significant.

.index will search for an item if given an item, but it can also take a tester function, as it does here.

.odd? returns whether a number is odd. Prefacing a symbol with & creates a function that calls the method associated with that symbol. So &:odd? is equivalent to ->(number) { number.odd? }.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Welcome to Code Golf, and nice answer! \$\endgroup\$ Jun 16 at 23:12
  • 1
    \$\begingroup\$ In Ruby, you don't need the parentheses in lambdas' parameter lists, so you can use ->n{(2**n).digits.index &:odd?} just fine \$\endgroup\$ Oct 3 at 15:31
  • \$\begingroup\$ @ConorO'Brien Thanks \$\endgroup\$
    – Matthias
    Oct 3 at 20:03
7
\$\begingroup\$

Python 2, 41 bytes

f=lambda n,c=1:2**n/c%2or-~f(n,c%2**n*10)

Try it online!

Function that terminates with ZeroDivisionError for no output. This happens when the power-of-10 c that we're using as a divisor is a multiple of 2**n, which causes c%2**n to reset to 0. This first happens for c=10**n, which is bigger than 2**n so we're already out of digits.

A probably-cheating version instead terminates with RuntimeError for exceeding the maximum recursion depth, though usually we pretend this doesn't exist since it would also trigger for very large inputs that should produce an output.

36 bytes

f=lambda n,c=1:2**n/c%2or-~f(n,c*10)

Try it online!

\$\endgroup\$
1
  • 4
    \$\begingroup\$ non cheating 37 \$\endgroup\$
    – loopy walt
    Jun 17 at 3:08
7
\$\begingroup\$

Julia 1.0, 32 bytes

!x=prod(findmax(digits(2^x).%2))

Try it online!

1-indexed, works for 0, and returns 0 for no odd digit

\$\endgroup\$
6
\$\begingroup\$

Haskell, 46 bytes

(succ<$>).findIndex(odd.ord).reverse.show.(2^)

Try it online!

\$\endgroup\$
1
  • 2
    \$\begingroup\$ Welcome to Code Golf, and nice answer! \$\endgroup\$ Jun 20 at 17:02
5
\$\begingroup\$

05AB1E, 8 5 bytes

oRÅΔÉ

0-indexed. Outputs -1 if there are no odd digits. Also works for \$n=0\$.

Try it online or verify the first 26 test cases.

Original 8 bytes approach:

oSÉRƶ0Kß

1-indexed. Outputs an empty string if there are no odd digits. Also works for \$n=0\$.

Try it online or verify the first 26 test cases.

Explanation:

o         # Push 2 to the power of the (implicit) input-integer
 R        # Reverse it
  ÅΔ      # Find the first 0-based index that's truthy for, or -1 if none are:
    É     #  Is the digit odd?
          # (after which the result is output implicitly)
o         # Push 2 to the power of the (implicit) input-integer
 S        # Convert it to a list of digits
  É       # Check for each digit whether it's odd (1 if odd; 0 if even)
   R      # Reverse this list
    ƶ     # Multiply each value by its 1-based index
     0K   # Remove all 0s
       ß  # Pop and keep the minimum, or an empty string if the list was empty
          # (which is output implicitly as result)
\$\endgroup\$
5
\$\begingroup\$

Vyxal gA, 7 5 bytes

Ef∷ṘT

Try it Online!

-2 thanks to @lyxal!

\$\endgroup\$
4
  • 2
    \$\begingroup\$ That's roughly what I came up with too. Nice job! \$\endgroup\$
    – lyxal
    Jun 16 at 10:49
  • \$\begingroup\$ You can use the g flag to get a 6 byter \$\endgroup\$
    – lyxal
    Jun 16 at 11:34
  • \$\begingroup\$ Also, answers can be 0-indexed apparently, so no need for the either. Hence you'd have Ef∷ṘT with g flag \$\endgroup\$
    – lyxal
    Jun 16 at 12:55
  • \$\begingroup\$ I don’t really like flags for golfing But I missed a 0-indexed permission, so let it all be together ;) \$\endgroup\$
    – lesobrod
    Jun 16 at 13:56
5
\$\begingroup\$

Arturo, 40 bytes

$=>[index reverse map digits^2&=>[&%2]1]

Try it!

0-indexed; no result returns null.

$=>[            ; a function where input is assigned to &
    ^2&         ; two raised to the input power
    digits      ; get its digits as a list
    map         ; map over the digits...
    =>[&%2]     ; ...modulo two
    reverse     ; reverse
    index ... 1 ; get the index of the leftmost 1
]               ; end function
\$\endgroup\$
5
\$\begingroup\$

Python 2, 53 bytes

lambda n:`[int(c)%2for c in`2**n`[::-1]]`.find('1')/3

An unnamed function that accepts a non-negative integer, \$n\$, and returns the 0-indexed position of the last odd digit of \$2^n\$, or \$-1\$ if all the digits are even.

Try it online!

Note: this actually gets scuppered at \$n=63\$ when long ints come into play and the representation of 2**n acquires a trailing L. However, this is about where floating point errors would creep in with division-based methods anyway (this errors while they may start giving incorrect results). This can be dealt with by inserting if'L'>c between the ]] for \$60\$.

\$\endgroup\$
5
\$\begingroup\$

Python 2, 46 45 53 bytes

-1 byte thanks to @The Thonnu
+8 bytes so it always terminates (added %(i-2*x))

i=2**input()
x=0
while~i/10**x%2%(i-2*x):x+=1
print x

Try it online!

Zero indexed, gives a ZeroDivisionError for \$n=1,2,3,6,11\$.

\$\endgroup\$
5
  • 1
    \$\begingroup\$ You can change the // to / for -1. \$\endgroup\$
    – The Thonnu
    Jun 16 at 16:38
  • \$\begingroup\$ Ah, my brain was still halfway stuck in python 3, thanks :) \$\endgroup\$ Jun 16 at 16:45
  • 1
    \$\begingroup\$ I feel like this should not be allowed, there is an explicit instruction not to output a positive integer when no digits are odd, this is like working around that ruling by never halting. (Also, how long does one wait before knowing the result?) If you error at the point it become too long I feel that should be acceptable. \$\endgroup\$ Jun 16 at 17:06
  • 3
    \$\begingroup\$ Unfortunately, OP has said solutions must terminate \$\endgroup\$
    – The Thonnu
    Jun 16 at 19:06
  • \$\begingroup\$ Fixed so it complies \$\endgroup\$ Jun 20 at 17:01
4
\$\begingroup\$

PARI/GP, 36 bytes

n->valuation(x*Pol(digits(2^n)%2),x)

Attempt This Online!

\$\endgroup\$
4
\$\begingroup\$

Thunno 2 M, 5 bytes

OdɗrV

Attempt This Online! or verify the first 20 test cases

0-indexed. Outputs [] if there is no odd digit. Works for \$n=0\$.

Explanation

OdɗrV  # Implicit input
O      # Push 2 ** input
 d     # Convert to digits
  ɗ    # Each mod 2
   r   # Reverse the list
    V  # Truthy indices
       # Take the minimum
       # Implicit output
\$\endgroup\$
4
\$\begingroup\$

Wolfram Language (Mathematica), 49 47 bytes

#&@@Reverse@IntegerDigits[2^#]~Position~_?OddQ&

Try it online!
-2 thanks to @att

\$\endgroup\$
1
  • \$\begingroup\$ 47 bytes \$\endgroup\$
    – att
    Jun 16 at 18:41
4
\$\begingroup\$

Bash, 42 bytes

i=$[2**n] i=${i#${i%[13579]*}}; echo ${#i}

Try it online!

\$\endgroup\$
3
\$\begingroup\$

R, 30 bytes

\(n)match(1,2^n%/%10^(0:n)%%2)

Attempt This Online!

\$\endgroup\$
3
\$\begingroup\$

MATL, 8 bytes

WVooPfX<

Output is empty if no solution.

Try it online! Or verify all test cases.

How it works

W    % Implicit input. 2 raised to that
V    % Convert to char vector
o    % Convert each char to code point
o    % Modulo 2
P    % Reverse
f    % Find: gives 1-based indices of non-zeros
X<   % Minimum. Implicit display
\$\endgroup\$
3
\$\begingroup\$

Nibbles, 7 bytes (14 nibbles)

/`?\`@~^2$%$~

Returns 0 if there are no odd digits.

/`?\`@~^2$%$~   # full program
             $  # with implicit arg added;
 `?             # find the indices of elements that are truthy by
          %$~   # modulo 2 (default)
                # of
   \            # reverse of
    `@~         # digits in base 10 (default) of
       ^2$      # 2^input
/               # finally fold over this list from right, returning
                # left element each time 
                # (so returns first element)

enter image description here

\$\endgroup\$
3
\$\begingroup\$

Python 2, 58 bytes

lambda n:"".join(`int(i)%2`for i in`2**n`[::-1]).find("1")

Attempt This Online!

Python 3, 65 bytes

lambda n:"".join(str(int(i)%2)for i in str(2**n)[::-1]).find("1")

Attempt This Online!

\$\endgroup\$
3
\$\begingroup\$

Scala, 53 bytes

Thanks for the comment to save so many bytes.

Try it online!

1-indexed. "return 0" means missing odd numbers.

BigInt(2).pow(_).toString.reverse.indexWhere(_%2>0)+1
\$\endgroup\$
1
  • \$\begingroup\$ You may use 0 to indicate missing odd numbers, so no need for the if and simple t+1 will do, I think. (I don't speak Scala, so probably this shortens the code more than just replacing the end bit) \$\endgroup\$
    – pajonk
    Jun 16 at 10:32
3
\$\begingroup\$

Brachylog, 13 bytes

;2^₍↔i%₂ʰℕ₁ʰt

Try it online!

Explanation

;2^₍             2^Input
    ↔            Reverse the number
     i           Take a [Digit, Index] of that number
      %₂ʰ        [Digit mod 2, Index]
         ℕ₁ʰ     Digit mod 2 must be in [1,+inf)
            t    Output = Index

would mess up indexing in case we reverse a number that ends with 0, but powers of 2 cannot have trailing 0.

\$\endgroup\$
3
\$\begingroup\$

Python 3.8 (pre-release), 46 (40) bytes

40 bytes if input is allowed to be \$n = 2^t\$ instead of \$t\$ (switched notation). After solving, I saw xnors answer which I think is similar but deals with the power of 2.

f=lambda n,j=1:j if n%2else f(n//10,j+1)

Try it online!

26 from xnor by accumulating using 1+f instead of j.

f=lambda n:n%2or-~f(n//10)

Using this in a \$2^\cdot\$ wrapper gives:

43 58:

lambda t:f(2**t)
f=lambda n:n%2or-~f(n//10)

Python 3.8 (pre-release), 46 bytes

f=lambda n,j=0:j if 2**n//10**j%2else f(n,j+1)

Try it online!

37 from xnor by accumulating using 1+f instead of j. (Identical except for n//j since python 3)

f=lambda n,j=1:2**n//j%2or-~f(n,j*10)
\$\endgroup\$
1
  • 2
    \$\begingroup\$ Nope, taking the \$2^t\$ is not allowed. \$\endgroup\$
    – pajonk
    Jun 20 at 4:50
3
\$\begingroup\$

Piet + ascii-piet, 154 bytes (11×14=154 codels)

tldfm?liafqaqQ      ?   i  I rrrjje   e  A ?        e  R biqaasccmu  _             Saeeumcccccc?sVi    qq      Vt    qq sss  Nd    qq  a   Clliqqqq??qfaks

Infinite loop for n = 0, 1, 2, 3, 6, 11, ... (No odd digits in n^2). Outputs correctly for anything with an odd digit. If you want to see how it works, make sure to add input n before executing.

Try Piet online!

\$\endgroup\$
2
\$\begingroup\$

Husk, 8 bytes

V%2↔d`^2

Try it online!

V           # Index of first element that is truthy when  
 %2         # modulo 2
   ↔        # of the reverse of
    d       # the decimal digits of
     `^2    # 2^input
\$\endgroup\$
2
\$\begingroup\$

C++ (gcc), 56 bytes

[](int&n){int p=1;for(n=1<<n;n%2-!!n;n/=10)++p;n=n?p:0;}

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Retina, 39 bytes

~`.+
.+¶$$.($&*$(2$*)_
-1L$`[13579]
$.'

Try it online! Link includes test cases. 0-indexed. Outputs nothing if no odd digit exists. Explanation:

.+
.+¶$$.($&*$(2$*)_

Replace the input with code to calculate that power of 2. (I could save two bytes by removing the )_ at the end but this actually prevents a crash in Retina which I feel is not an ideal way to handle zero input.)

~`

Execute the code to generate the power of 2.

-1L$`[13579]

Match the last odd digit.

$.'

Output the number of digits after it.

\$\endgroup\$
2
\$\begingroup\$

Japt -g, 9 bytes

0-indexed, returns undefined if there's no odd digits

õ!²Ìì Ôðu

Try it

õ!²Ìì Ôðu     :Implicit input of integer U
õ             :Range [1,U]
 !²           :Raise 2 to the power of each
   Ì          :Last element
    ì         :Digit array
      Ô       :Reverse
       ð      :0-based indices of elements that truthy (1)
        u     :  Mod 2
              :Implicit output of first element
\$\endgroup\$
2
\$\begingroup\$

Charcoal, 12 bytes

I⌕⮌﹪↨X²Nχ²¦¹

Try it online! Link is to verbose version of code. 0-indexed. Outputs -1 if no odd digit exists. Explanation:

      ²         Literal integer `2`
     X          Raised to power
       N        Input integer
    ↨           Converted to base
        χ       Predefined variable `10`
   ﹪            Vectorised modulo
         ²      Literal integer `2`
  ⮌             Reversed
 ⌕              Find index of
           ¹    Literal integer `1`
                Implicitly print

Actually outputting the last odd digit also takes 12 bytes:

FIX²N¿﹪Iι²Pι

Try it online! Link is to verbose version of code. Outputs nothing if no odd digit exists. Explanation:

FIX²N

Loop over the digits.

¿﹪Iι²

If the digit is odd, then...

Pι

... overprint any previous result.

\$\endgroup\$
2
\$\begingroup\$

Desmos, 50 bytes

I=[0...nlog2]
f(n)=I[mod(floor(2^n/10^I),2)=1].min

Counting starts from 0 instead of 1, which is allowed as per the OP. Outputs undefined for all-even digits.

Try It On Desmos!

Try It On Desmos! - Prettified

\$\endgroup\$
2
\$\begingroup\$

JavaScript, 61 bytes

Nearly double the length of the other JS answer (and a slightly more naive implementation), but spent a bit of time on it, so might as well post it.

Returns -0 when there is no odd digit.

n=>-(~(l=(z=[...2**n+'']).findLastIndex(i=>i%2))&&l-z.length)

Attempt This Online!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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