| Bytes | Lang | Time | Link |
|---|---|---|---|
| 007 | Vyxal 3 | 250505T215726Z | Weird Gl |
| 013 | Dyalog APL | 250504T024657Z | Aaron |
| 052 | Python 2 | 230616T162948Z | Jonathan |
| 035 | Perl 5 p | 250416T214036Z | Xcali |
| 061 | Swift 5.9 | 230713T001320Z | macOSist |
| 115 | Go | 240529T212309Z | bigyihsu |
| nan | Piet + asciipiet | 230627T175645Z | Sanguine |
| 015 | Uiua | 231224T061039Z | chunes |
| 031 | Ruby | 230616T231138Z | Matthias |
| 008 | Pip | 231002T025748Z | DLosc |
| 020 | x86 | 230718T195010Z | Hunaphu |
| 031 | Raku | 230717T223531Z | bb94 |
| 182 | Racket – | 230714T191827Z | Ed The & |
| 4640 | Python 3.8 prerelease | 230619T193359Z | Hunaphu |
| 046 | Haskell | 230620T164339Z | don_aman |
| 050 | Excel | 230616T143005Z | Jos Wool |
| 053 | Python 2 | 230616T162942Z | CursorCo |
| 022 | BQN | 230620T072112Z | Dominic |
| 026 | J | 230620T035802Z | south |
| 061 | JavaScript | 230619T224826Z | code |
| 013 | Brachylog | 230619T093227Z | Fatalize |
| 050 | Desmos | 230618T013045Z | Aiden Ch |
| 042 | Bash | 230617T073755Z | noname |
| 047 | Wolfram Language Mathematica | 230616T095512Z | lesobrod |
| 005 | Thunno 2 M | 230616T152401Z | The Thon |
| 012 | Charcoal | 230616T135732Z | Neil |
| 040 | Arturo | 230616T224004Z | chunes |
| 032 | Julia 1.0 | 230616T222256Z | MarcMush |
| 053 | Scala | 230616T102735Z | 138 Aspe |
| 041 | Python 2 | 230616T191753Z | xnor |
| 035 | JavaScript ES7 | 230616T092258Z | Arnauld |
| 058 | Python 2 | 230616T160109Z | The Thon |
| 009 | Japt g | 230616T110706Z | Shaggy |
| 039 | Retina | 230616T140931Z | Neil |
| 005 | Vyxal gA | 230616T093504Z | lesobrod |
| 064 | Python 2 | 230616T135522Z | ElPedro |
| 056 | C++ gcc | 230616T111907Z | Noodle9 |
| 005 | 05AB1E | 230616T113300Z | Kevin Cr |
| 714 | Nibbles | 230616T105303Z | Dominic |
| 008 | MATL | 230616T104634Z | Luis Men |
| 008 | Husk | 230616T103252Z | Dominic |
| 030 | R | 230616T102551Z | Dominic |
| 036 | PARI/GP | 230616T101438Z | alephalp |
Vyxal 3, 10 7 bytes
Ef⍢⇄Ṭg›
Ef⍢⇄Ṭg›
Ef # Split into digits
⍢⇄Ṭg› # Get minimum index for an odd digit (1-indexed)
💎
Created with the help of Luminespire.
Dyalog APL, 13 bytes
{⊃⍸⌽2|⍎¨⍕2*⍵}
2*⍵ ⍝ 2^n
⍕ ⍝ as a string
⍎¨ ⍝ Execute each character independently to get a vector of digits
2| ⍝ Modulo 2
⌽ ⍝ Reverse the list
⍸ ⍝ Index of non-zero
⊃ ⍝ Take the first one
Python 2, 52 bytes
-1 and removal of issues with longs thanks to Lucenaposition!
lambda n:[int(c)%2for c in str(2**n)[::-1]].index(1)
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.
Swift 5.9, 70 68 61 bytes
let o={"\(2<<($0-1))".reversed().index{Int("\($0)")!%2>0}!+1}
0-indexed, throws a force-unwrap error when there aren't any odd characters.
Throws a deprecation warning when compiling on modern Swift versions; ignore it.
Go, 115 bytes
import(."fmt";."strings")
func f(n int)int{s:=Sprint(1<<n)
l:=LastIndexAny(s,"13579")
if l>=0{l=len(s)-l}
return l}
Input n, calculates 2^n, converts it to a string, and then uses the builtin strings.LastIndexAny to get the last odd digit. However, this is unhelpfully 0-indexed from the front, so if there are odd digits (l>=0) we change it to index from the back by subtracting the index from the length of the power of 2.
Outputs the location, 1-indexed.
Go, 114, 112 bytes
import."fmt"
func f(n int)int{s:=Sprint(1<<n)
for i:=range len(s){if(s[len(s)-i-1]-'0')%2>0{return i}}
return-1}
Without using the strings builtin. 0-indexed.
- -2 by using Go 1.22+ range-over-int.
Piet + ascii-piet, 154 112 bytes (8×14=112 codels)
ttlqrjmbjbrjdA vv?uier bsquAd?if qkkdqr?aQllrbjfncl? aL lccj nst dd Dq mtvse t dnkTqiarjjjbus fkNr?lmilmnks?ffi
Shaved off 42 bytes (almost 30 percent!) by actually trying to golf it. Removed a lot of useless codels. It's actually impossible to understand just by looking at it now, but it's shorter.
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.
Original 154 bytes (11x14=154 codels)
tldfm?liafqaqQ ? i I rrrjje e A ? e R biqaasccmu _ Saeeumcccccc?sVi qq Vt qq sss Nd qq a Clliqqqq??qfaks
Uiua, 15 bytes
⬚∞⊢⊚⇌◿2-@0°⋕ⁿ:2
0-indexed; returns ∞ for no answer.
⬚∞⊢⊚⇌◿2-@0°⋕ⁿ:2
ⁿ:2 # 2 to the input power
°⋕ # unparse
-@0 # convert to digits
◿2 # modulo 2
⇌ # reverse
⊚ # indices of 1s
⬚∞⊢ # first one, or infinity if none exist
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? }.
Pip, 8 bytes
R%*Ea@?1
Outputs 0-indexed: e.g., the output for 2^12 (4096) is 1. Outputs nothing if there is no odd digit.
Explanation
R%*Ea@?1
a ; Command-line argument
E ; 2 to that power
%* ; Take each digit mod 2
R ; Reverse
@?1 ; Find index of first occurrence of 1
x86, 20 bytes
Assumes input is in ecx and that edx is cleared.
B3 0A B0 01 D3 E0 B1 01 F7 FB 89 C2 FF C1 83 E2 01 74 F5 C3
mov $10, %bl; # b = divisor
mov $1, %al; # a = 1
shll %cl, %eax; # a = 1<<n = 2**n
mov $1, %cl; # c = 1, first digit is always even
loop:
idiv %ebx; # a / 10
movl %eax, %edx; # a->d for comparison / clearing
incl %ecx; # c += 1
andl $1, %edx; # a % 2, clears edx if 0, otherwise loop is over
jz loop; # if a%2 == 0, loop again
Racket – 182 bytes
(define(f n)(let l([L(reverse(map(λ(c)(-(char->integer c)48))(string->list(number->string(expt 2 n)))))][I 0])(cond[(odd?(list-ref L I))I][(>(-(length L)1)I)(l L(+ I 1))][#t 'na])))
Explanation
We first obtain the list of digits in reversed order of the number \$ 2^n \$ and start the index at 0 since Racket uses 0-based indexing. When we convert the number from a string to a list, the digits are represented in ASCII characters. So to extract the digits numeric value we need to subtract 48 from the character's ASCII value (48 in ASCII is the character 0).
(define (last-odd n)
(let loop ([lst (reverse (map (lambda (char) (- (char->integer char) 48))
(string->list (number->string (expt 2 n)))))]
[index 0])
...))
Once we have the list of reversed digits, we can begin looping. We create a conditional statement that checks if the current digit is odd. If it is, we return the index. If it isn't odd, we move on to the next check which checks whether we can still loop through the list. If we can, great, we then loop. If all fails, we return 'na.
(define (last-odd n)
(let loop ([lst (reverse (map (lambda (char) (- (char->integer char) 48))
(string->list (number->string (expt 2 n)))))]
[index 0])
(cond [(odd? (list-ref lst index)) index]
[(> (sub1 (length lst)) index) (loop lst (add1 index))]
[#t 'na])))
Conclusion
I'd like to end this off with an interesting experiment. I'd like to see how this function looks like on a plot. To do this, we can import Racket's plot library:
(require plot)
Now to customize our plot, we can use parameterize to set configurations.
(require plot)
(parameterize ([plot-width 600]
[plot-height 480]
[plot-title "Plot that shows the positions of the last odd digit in 2^n (0 been the last digit)."]
[plot-x-label "n"]
[plot-y-label "Last odd digit."]
[plot-new-window? #t])
...)
This will open a new window, set its title, set the label of the x and y axes and set the width and height of the plot. Cool! Now how do we draw on the plot? Simple!
Racket's plot package has a function called plot that plots what ever renderer is in its argument. Since we are using a line graph, we use a line renderer called lines.
(plot (lines ...))
This renderer receives a sequence of vector points in the form of #(x y). We can programmatically define this sequence using a for/fold loop.
(plot (lines (for/fold ([lst empty]) ([index (in-range 0 200)])
(let ([result (f index)])
(cons (vector index (if (equal? 'na result) 0 result))
lst)))))
The first argument of the loop is an empty list called lst that will be filled after each iteration. The index argument is an iterator that is constructed before the iteration begins. If index reaches 199, the loop stops and lst is returned.
cons prepends a value to an existing list. In our case we create a new vector in the form of #(x y) where x is the current index value and y is the result of (f index). We then prepend this new vector to lst and replace the old lst with the new list by returning the constructed list.
Putting this all together:
#lang racket
; -- Paste in the golfed code -- ;
(require plot)
(parameterize ([plot-width 600]
[plot-height 480]
[plot-title "Plot that shows the positions of the last odd digit in 2^n (0 been the last digit)."]
[plot-x-label "n"]
[plot-y-label "Last odd digit."]
[plot-new-window? #t])
(plot (lines (for/fold ([lst empty]) ([index (in-range 0 200)])
(let ([result (f index)])
(cons (vector index (if (equal? 'na result) 0 result))
lst))))))
Which renders the following:
Pretty interesting! Have an amazing weekend!
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)
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)
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)
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.
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
Zero indexed, gives a ZeroDivisionError for \$n=1,2,3,6,11\$.
BQN, 22 bytes
1⊸+|1+·⊐⟜1∘⌊2|2⊸⋆÷10⋆↕
First find the 0-based index of the first odd digit of the power-of-2 of input 𝕩 (or return 𝕩 if all digits are even):
⊐⟜1∘⌊2|2⊸⋆÷10⋆↕
2⊸⋆ # 2 to the power of input
÷ # divided by
10 # 10
⋆ # to the power of
↕ # range from 0..input;
| # modulo
2 # 2;
⌊ # floor;
∘ # applied to
⊐⟜1 # find first instance of 1
Then fix the cases with all-even digits: change to 1-based indices and output this modulo 𝕩+1 (so all-even-digit inputs become zero):
1⊸+|1+·
· # last result
1+ # add 1;
| # modulo;
1⊸+ # input plus 1
J, 26 bytes
2{.^:$@I.@:|2x,.@|.&.":@^]
0-indexed. Returns an empty array for no odd digit.
2{.^:$@I.@:|2x,.@|.&.":@^]
2x ^] NB. 2^input using extended precision literal
@ NB. then
,.@|.&.": NB. stringify→reverse then columnize→convert to int
2 | NB. mod 2 the resulting digit list
@: NB. then
I. NB. find truthy indices
@ NB. then
{.^:$ NB. get first item, {., if, ^:, the rank, $, is not 0.
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)
Brachylog, 13 bytes
;2^₍↔i%₂ʰℕ₁ʰt
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.
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.
Wolfram Language (Mathematica), 49 47 bytes
#&@@Reverse@IntegerDigits[2^#]~Position~_?OddQ&
Try it online!
-2 thanks to @att
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
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.
Arturo, 40 bytes
$=>[index reverse map digits^2&=>[&%2]1]
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
Julia 1.0, 32 bytes
!x=prod(findmax(digits(2^x).%2))
1-indexed, works for 0, and returns 0 for no odd digit
Scala, 53 bytes
Thanks for the comment to save so many bytes.
1-indexed. "return 0" means missing odd numbers.
BigInt(2).pow(_).toString.reverse.indexWhere(_%2>0)+1
Python 2, 41 bytes
f=lambda n,c=1:2**n/c%2or-~f(n,c%2**n*10)
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)
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)
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)
Python 2, 58 bytes
lambda n:"".join(`int(i)%2`for i in`2**n`[::-1]).find("1")
Python 3, 65 bytes
lambda n:"".join(str(int(i)%2)for i in str(2**n)[::-1]).find("1")
Japt -g, 9 bytes
0-indexed, returns undefined if there's no odd digits
õ!²Ìì Ôðu
õ!²Ìì Ôð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
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.
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)
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)
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
Husk, 8 bytes
V%2↔d`^2
V # Index of first element that is truthy when
%2 # modulo 2
↔ # of the reverse of
d # the decimal digits of
`^2 # 2^input

