# Last odd digit of power of 2

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.

• 14 answers and 7 votes... Imho you don’t have to vote for everything, but if you answer... Jun 16, 2023 at 14:02
• @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. Jun 16, 2023 at 14:21
• @lesobrod That's one of my pet peeves here. How can a challenge be worth answering but not worth upvoting? Jun 16, 2023 at 14:39
• 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? Jun 16, 2023 at 16:35
• @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. Jun 16, 2023 at 18:08

# 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!

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

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

• 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.
– JvdV
Jun 20, 2023 at 14:45
• @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? Jun 20, 2023 at 19:32
• 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!
– JvdV
Jun 20, 2023 at 21:02

# 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? }.

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

# 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!

• non cheating 37 Jun 17, 2023 at 3:08

# 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

(succ<$>).findIndex(odd.ord).reverse.show.(2^)  Try it online! • Welcome to Code Golf, and nice answer! Jun 20, 2023 at 17:02 # 05AB1E, 8 5 bytes oRÅΔÉ  0-indexed. Outputs -1 if there are no odd digits. Also works for $$\n=0\$$. Original 8 bytes approach: oSÉRƶ0Kß  1-indexed. Outputs an empty string if there are no odd digits. Also works for $$\n=0\$$. 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)  # VyxalgA, 7 5 bytes Ef∷ṘT  Try it Online! -2 thanks to @lyxal! • That's roughly what I came up with too. Nice job! Jun 16, 2023 at 10:49 • You can use the g flag to get a 6 byter Jun 16, 2023 at 11:34 • Also, answers can be 0-indexed apparently, so no need for the › either. Hence you'd have Ef∷ṘT with g flag Jun 16, 2023 at 12:55 • I don’t really like flags for golfing But I missed a 0-indexed permission, so let it all be together ;) Jun 16, 2023 at 13:56 # 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  # Python 2, 53 bytes lambda n:[int(c)%2for c in2**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\$$. # Python 2, 4645 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\$$. • You can change the // to / for -1. Jun 16, 2023 at 16:38 • Ah, my brain was still halfway stuck in python 3, thanks :) Jun 16, 2023 at 16:45 • 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. Jun 16, 2023 at 17:06 • Unfortunately, OP has said solutions must terminate Jun 16, 2023 at 19:06 • Fixed so it complies Jun 20, 2023 at 17:01 # PARI/GP, 36 bytes n->valuation(x*Pol(digits(2^n)%2),x)  Attempt This Online! # Thunno 2M, 5 bytes OdɗrV  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  # Wolfram Language (Mathematica), 49 47 bytes #&@@Reverse@IntegerDigits[2^#]~Position~_?OddQ&  Try it online! -2 thanks to @att • 47 bytes – att Jun 16, 2023 at 18:41 # Bash, 42 bytes i=$[2**n] i=${i#${i%[13579]*}}; echo ${#i}  Try it online! # R, 30 bytes \(n)match(1,2^n%/%10^(0:n)%%2)  Attempt This Online! # MATL, 8 bytes WVooPfX<  Output is empty if no solution. ### 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  # 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)


# Python 2, 58 bytes

lambda n:"".join(int(i)%2for i in2**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!

# 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

• 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) Jun 16, 2023 at 10:32

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

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

• Nope, taking the $2^t$ is not allowed. Jun 20, 2023 at 4:50

# 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!

# 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


# 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!

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

# 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


# Charcoal, 12 bytes

Ｉ⌕⮌﹪↨Ｘ²Ｎχ²¦¹


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

      ²         Literal integer 2
Ｘ          Raised to power
Ｎ        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:

ＦＩＸ²Ｎ¿﹪Ｉι²Ｐι


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

ＦＩＸ²Ｎ


Loop over the digits.

¿﹪Ｉι²


If the digit is odd, then...

Ｐι


... overprint any previous result.

# 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

# 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!