# Replace twos with threes

Given a positive integer n write some code to take its prime factorization and replace all of its factors of 2 with 3.

For example

12 = 2 * 2 * 3 -> 3 * 3 * 3 = 27


This is so the goal is to minimize the byte count of your answer.

# Test cases

1 -> 1
2 -> 3
3 -> 3
4 -> 9
5 -> 5
6 -> 9
7 -> 7
8 -> 27
9 -> 9
10 -> 15
11 -> 11
12 -> 27
13 -> 13
14 -> 21
15 -> 15
16 -> 81
17 -> 17
18 -> 27
19 -> 19
20 -> 45
21 -> 21
22 -> 33
23 -> 23
24 -> 81
25 -> 25
26 -> 39
27 -> 27
28 -> 63
29 -> 29


# Fractran, 3 bytes

3/2


Fractran literally only has one builtin, but it happens to do exactly what this task is asking for. (It's also Turing-complete, by itself.)

The language doesn't really have a standardised syntax or interpreter. This interpreter (in a comment to a blog post – it's a very simple language) will accept the syntax shown here. (There are other Fractran interpreters with other syntaxes, e.g. some would write this program as 3 2, or even using 3 and 2 as command line arguments, which would lead to a score of 0+3 bytes. I doubt it's possible to do better than 3 in a pre-existing interpreter, though.)

## Explanation

3/2
/   Replace a factor of
2  2
3    with 3
{implicit: repeat until no more replacements are possible}

• Talk about right tool for the job.. – Kevin Cruijssen May 5 '17 at 7:02
• "Don't upvote trivial solutions that only uses a simple builtin." Well, in this case: Knowing that there's a language "Fractran" that has a single builtin that solves this specific task is by itself impressive. – Stewie Griffin May 5 '17 at 8:51
• Related SO code golf (pre-PPCG): Write a Fractran interpreter. – hobbs May 8 '17 at 5:29
• @AnderBiguri: Likely looking for a Turing-complete language that's very simple/easy to implement. Fractran is really elegant as Turing tarpits go; most have a lot more rough edges, special cases, or details that could be changed without making a large difference. – user62131 May 8 '17 at 13:25
• @AnderBiguri It looks like it came out of his studies of the Collatz conjecture; he proved that a generalization of Collatz is equivalent to Fractran and that Fractran is Turing-complete, therefore generalized Collatz is undecidable. – hobbs May 8 '17 at 18:00

# Python 2, 28 bytes

f=lambda n:n%2*n or 3*f(n/2)


Try it online!

Recursively divide the number by 2 and multiplies the result by 3, as long as the number is even. Odd numbers return themselves.

32 byte alt:

lambda n:n*(n&-n)**0.58496250072


Try it online. Has some float error. The constant is log_2(3)-1.

Uses (n&-n) to find the greatest power-of-2 factor of n, the converts 3**k to 2**k by raising it to the power of log_2(3)-1.

• Nice this is my solution exactly! – Sriotchilism O'Zaic May 4 '17 at 21:50
• @WheatWizard Me as well, aha! – Graviton May 5 '17 at 4:26

# 05AB1E, 4 bytes

Ò1~P


Try it online!

### How it works

Ò     Compute the prime factorization of the input.
1~   Perform bitwise OR with 1, making the only even prime (2) odd (3).
P  Take the product of the result.

• This beats Jelly by 1 byte simply because prime factorization is only one byte here :( – HyperNeutrino May 4 '17 at 23:43
• @HyperNeutrino: I noticed that too: "why is Dennis using 05AB1E? Oh, identical algorithm, shorter builtin names". So I had to go and find a language where I could do it in even fewer bytes, via the use of an even more appropriate set of builtins. – user62131 May 5 '17 at 0:05

until odd$(*3).(div2)  The divide by two and multiply by 3 until odd trick in Haskell. Try it online! Alternative with a lambda instead of a pointfree function and with the same byte count: odduntil\x->div(x*3)2  Edit: @ais523 saved a byte in the original version and @Ørjan Johansen one in the alternative version, so both version have still the same length. Thanks! • The lambda version can be shortened to odduntil\x->div(x*3)2. – Ørjan Johansen May 4 '17 at 23:55 • The original version can also be shortened one byte via using $ to replace a pair of parentheses: Try it online! – user62131 May 5 '17 at 3:39
• @ØrjanJohansen: ah, nice! Thanks. – nimi May 5 '17 at 5:04
• @ais523: How could I have missed that one, Thanks! – nimi May 5 '17 at 5:05
• I think you forgot to remove a pair of () from the lambda version – CAD97 May 5 '17 at 6:41

## JavaScript (ES6), 19 bytes

f=x=>x%2?x:f(x*1.5)


While the input is divisible by two, multiplies it by 1.5, which is equivalent to dividing by 2 and multiplying by 3.

• x*3/2 has the same bytecount – Leaky Nun May 5 '17 at 3:42
• f= is usally not needed for js. – Christoph May 5 '17 at 6:18
• @Christoph Thanks, but in order to call itself f(x*1.5) it needs to have the name f, hence why the f= is included. – ETHproductions May 5 '17 at 11:45
• @ETHproductions Uhm ... of course ! I missed that. Is there any meta on what the calling code exactly looks like? – Christoph May 5 '17 at 12:17
• @Christoph Here is the relevant meta post. – ETHproductions May 5 '17 at 14:48

# Brain-Flak, 76 bytes

{{({}[()]<([({})]()<({}{})>)>)}{}([{}]()){{}((({})){}{})<>}<>}<>({}({}){}())


Try it online!

## Explanation

This program works by dividing the number by two and tripling until it gets a remainder of one from the division. Then it stops looping and doubles and adds one to the final number.

# Mathematica, 22 19 bytes

Thanks to lanlock4 for saving 3 bytes!

#//.x_?EvenQ:>3x/2&


Pure function that does the replacement repeatedly, one factor of 2 at a time. Works on all positive integers less than 265537.

• Would x_?EvenQ work instead of x_/;EvenQ@x? – Not a tree May 5 '17 at 3:25
• You're totally right, thanks! – Greg Martin May 5 '17 at 4:23

# MATL, 7, 6 bytes

Yf1Z|p


Try it online!

1 byte saved thanks to Dennis's genius observation

The best way to explain this is to show the stack at various points.

Yf  % Prime factors

[2 2 2 3]

1Z| % Bitwise OR with 1

[3 3 3 3]

p   % Product

81


Alternate solution:

Yfto~+p

• Nice! I had Yf3H$X>p for 8 bytes – Luis Mendo May 4 '17 at 22:20 # 05AB1E, 6 5 bytes Saved a byte thanks to Adnan. ÒDÈ+P  Try it online! Explanation Ò # push list of prime factors of input D # duplicate È # check each factor for evenness (1 if true, else 0) + # add list of factors and list of comparison results P # product  • ÒDÈ+P should save a byte – Adnan May 4 '17 at 22:28 • @Adnan: Thanks! – Emigna May 5 '17 at 6:02 ## Alice, 9 bytes 2/S 3 o@i  Try it online! Alice has a built-in to replace a divisor of a number with another. I didn't think I'd actually get to make use of it so soon... Using the code points of characters for I/O, this becomes 6 bytes: I23SO@. ### Explanation 2 Push 2 (irrelevant). / Reflect to SE. Switch to Ordinal. i Read all input as a string. The IP bounces up and down, hits the bottom right corner and turns around, bounces down again. i Try to read more input, but we're at EOF so this pushes an empty string. / Reflect to W. Switch to Cardinal. 2 Push 2. The IP wraps around to the last column. 3 Push 3. S Implicitly discard the empty string and convert the input string to the integer value it contains. Then replace the divisor 2 with the divisor 3 in the input. This works by multiplying the value by 3/2 as long as it's divisible by 2. / Reflect to NW. Switch to Ordinal. Immediately bounce off the top boundary. Move SW. o Implicitly convert the result to a string and print it. Bounce off the bottom left corner. Move NE. / Reflect to S. Switch to Cardinal. @ Terminate the program.  • Your obsession is officially confirmed. – Leaky Nun May 5 '17 at 3:38 # Jelly, 8 5 bytes Æf3»P Æf3»P Main Link, argument is z Æf Prime factors 3» Takes maximum of 3 and the value for each value in the array P Takes the product of the whole thing  Try it online! -3 bytes thanks to a hint from @Dennis! • Hint: 2 is both the only even and the smallest prime number. – Dennis May 4 '17 at 22:15 • @Dennis I see. Yes, got it now. Thanks! :) – HyperNeutrino May 4 '17 at 23:42 • Congratulations on learning Jelly. – Leaky Nun May 5 '17 at 3:49 • @LeakyNun Thanks! And thanks for teaching it to me. :) – HyperNeutrino May 5 '17 at 3:50 • Congrats on this answer! – Erik the Outgolfer May 7 '17 at 11:08 # Pyth - 1410 9 bytes *^1.5/PQ2  Counts the number of 2s in the prime factorization (/PQ2). Multiplies the input by 1.5^(# of 2s) Try it • Interesting approach - too bad it's not as short as the existing Pyth solution. – Esolanging Fruit May 5 '17 at 2:31 • @Challenger5 I'm not seeing any other Pyth solution here. – Maria May 5 '17 at 4:25 • Oh, OK then. It's a more interesting approach than the typical one for this challenge. – Esolanging Fruit May 5 '17 at 4:27 # Java, 38 bytes int f(int n){return n%2>0?n:f(n/2*3);}  Try it online! Previous 43-byte solution: int f(int n){for(;n%2<1;)n=n/2*3;return n;}  Try it online! # Hexagony, 112 91 bytes Grid size 6 (91 bytes)  ? { 2 . . < / = { * = \ " . & . . . { _ ' . . { . . } ' * 2 _ } { / . } & . ! " . > % . . < | . . @ | \ . . \ . | ~ . . 3 . . " . } . " . " . & . \ = & / 1 \ = { : = } . [ = { { { <  Compact version ?{2..</={*=\".&...{_'..{..}'*2_}{/.}&.!".>%..<|..@|\..\.|~..3..".}.".".&.\=&/1\={:=}.[={{{<  Grid size 7 (112 bytes)  ? { 2 " ' 2 < / { * \ / : \ " . = . = . = | . 3 / & / { . . } { . " . >$ } { { } / = . 1
_ . . } . . _ . . & . {
. > % < . . ~ & . . " . |
| . . } - " . ' . @ | {
. . . = & . . * ! . {
. . . _ . . . _ . =
> 1 . . . . . < [
. . . . . . . .
. . . . . . .


Try it online!

Compact Version:

?{2"'2</{*\/:\".=.=.=|.3/&/{..}{.".>$}{{}/=.1_..}.._..&.{.>%<..~&..".||..}-".'.@|{...=&..*!.{..._..._.=>1.....<[  Ungolfed Version for better readability: Approximate Memory Layout Grey Path (Memory initialization) ? Read input as integer (Input) { Move to memory edge "Divisor left" 2 Set current memory edge to 2 " ' Move to memory edge "Divisor right" 2 Set current memory edge to 2 " Move to memory edge "Multiplier" 3 Set current memory edge to 3 " Move to memory edge "Temp 2" 1 Set current memory edge to 1 { { { Move to memory edge "Modulo" = Turn memory pointer around [ Continue with next instruction pointer  Loop entry % Set "Modulo" to Input mod Divisor < Branch depending on result  Green Path (value is still divisible by 2) } } { Move to memory edge "Result" = Turn memory pointer around * Set "Result" to "Temp 2" times "Multiplier" (3) { = & Copy "Result" into "Temp2" { { } } = Move to "Temp" : Set "Temp" to Input / Divisor (2) { = & Copy "Temp" back to "Input" " Move back to "Modulo"  Red Path (value is no longer divisible by 2) } = & " ~ & ' Drag what's left of "Input" along to "Multiplier" * Multiply "Multiplier" with "Temp 2" ! @ Output result, exit program  • Welcome to PPCG! :) – Martin Ender Mar 23 '18 at 11:12 • @MartinEnder Thanks, awesome language btw. :) – Manfred Radlwimmer Mar 23 '18 at 11:13 • Thanks for using it! :) Can't you simplify the memory layout (and thereby the amount of movement you need to do) if you compute %2 and :2 both into the "modulo" edge? (So you can just get rid of the top two edges.) And then, could you attach the "multiplier" branch onto the "modulo" edge instead of the "divisor" edge so you need less movement after each branch? (You could possibly even rotate that section, so that "result" or "temp 2" touches "modulo" which would mean you only need to copy the final result once before being able to compute the product.) – Martin Ender Mar 23 '18 at 11:20 • @MartinEnder Uhhhm probably. I'm still getting around the "Agony" part of the language so for now I'll probably stick to making the grid smaller without touching the logic ^^ – Manfred Radlwimmer Mar 23 '18 at 11:35 # Retina, 23 bytes .+$*
+^(1+)\1&$1 1  Try it online! # Brachylog, 7 bytes ~×₂×₃↰|  Try it online! ## How it works ~×₂×₃↰| original program ?~×₂×₃↰.|?. with implicit input (?) and output (.) added ?~×₂ input "un-multiplied" by 2 ×₃ multiplied by 3 ↰ recursion . is the output | or (in case the above fails, meaning that the input cannot be "un-multiplied" by 2) ?. the input is the output  • – user62131 May 5 '17 at 10:27 # J, 11 bytes [:*/q:+2=q:  Try it online! [: cap (placeholder to call the next verb monadically) */ the product of q: the prime factors + plus (i.e. with one added where) 2 two = is equal to (each of) q: the prime factors • I thought you find [: disgusting. – Leaky Nun May 5 '17 at 3:39 • @LeakyNun I do, but I wasn't as clever as Conor O'Brien. – Adám May 5 '17 at 5:37 # J, 1512 10 bytes (+2&=)&.q:  Try it online! Works similar to below, just has different logic concerning replacement of 2 with 3. # 15 bytes (2&={,&3)"+&.q:  Try it online! ## Explanation (2&={,&3)"+&.q: &. "under"; applies the verb on the right, then the left, then the inverse of the right q: prime factors ( )"+ apply inside on each factor ,&3 pair with three: [factor, 3] 2&= equality with two: factor == 2 { list selection: [factor, 3][factor == 2] gives us 3 for 2 and factor for anything else &.q: under prime factor  • Huh, you switched algorithm while I was writing up mine. Now we use the same. – Adám May 4 '17 at 22:24 • @Adám Oh, haha. Nice answer! I couldn't resist the opportunity to use roll here. :) – Conor O'Brien May 4 '17 at 22:26 • Actually I might be able to save some more bytes...edit saved some :D – Conor O'Brien May 4 '17 at 22:27 • Funny you call it Roll, I call it Under. Hope to get it into APL soon. – Adám May 4 '17 at 22:28 • @Adám Haha it's actually called under. I got the terms confused – Conor O'Brien May 4 '17 at 22:29 # Pyth, 9 bytes Integer output \o/ *F+1.|R1P  ## How it works *F+1.|R1P P prime factorization .|R1 bitwise OR each element with 1 *F+1 product  # Japt, 19 16 10 9 7 bytes k ®w3Ã×  Try it online! # Explanation  k ® w3Ã × Uk mZ{Zw3} r*1 U # (input) k m # for every prime factor Z{Zw3} # replace it by the maximum of itself and 3 r*1 # output the product  • Hah, JS is tied with Japt. A sure sign there's a much shorter solution ;-) – ETHproductions May 4 '17 at 21:55 • Hints: × is a shortcut for r@X*Y}1 (or just r*1), which might come in handy. There's also XwY which is Math.max(X,Y). – ETHproductions May 4 '17 at 21:59 • Thanks, though the recursive solution really is the shortest. – Luke May 4 '17 at 22:05 • Nice one! I think you can do k m_w3Ã× to save a byte. Also, m_ can be shortened to ®. – Oliver May 5 '17 at 0:43 # PHP, 36 Bytes for($a=$argn;$a%2<1;)$a*=3/2;echo$a;


Try it online!

• for($a=$argn;!1&$a;)$a*=3/2;echo$a; renaming $argn saves a single byte. – Christoph May 5 '17 at 6:24

## CJam, 10 9 bytes

rimf1f|:*


Really simple.

Explanation:

ri  e# Read integer:         | 28
mf  e# Prime factors:        | [2 2 7]
1   e# Push 1:               | [2 2 7] 1
f|  e# Bitwise OR with each: | [3 3 7]
:*  e# Product:              | 63


# Hexagony, 28 27 26 bytes

?'2{{(\}}>='!:@=$\%<..>)"*  Try it online! Laid out:  ? ' 2 { { ( \ } } > = ' ! : @ =$ \ % < . .
> ) " * . .
. . . . .
. . . .


This basically runs:

num = input()
while num%2 == 0:
num = (num/2)*3
print num


At this point it's an exercise on how torturous I can get the loop path to minimise bytes.

• Well damn, I didn't think of that – Manfred Radlwimmer Mar 23 '18 at 12:04
• @ManfredRadlwimmer Don't worry, coding anything in Hexagony is an achievement in itself – Jo King Mar 23 '18 at 12:28

# Japt, 7 bytes

k mw3 ×


Try it online!

### Explanation

k mw3 ×

k        // Factorize the input.
mw3    // Map each item X by taking max(X, 3).
×  // Take the product of the resulting array.
// Implicit: output result of last expression


# APL (Dyalog Unicode), 26 bytes

{⍵(⊣×(3*⊢)×(÷2*⊢))2⍟⍵∨2*⍵}


Try it online!

This is too verbose, I must be doing something wrong...

# R, 42 bytes

The only right amount of bytes in an answer.

x=gmp::factorize(scan());x[x==2]=3;prod(x)


Pretty straightforward, uses the gmp package to factorize x, replaces 2s by 3s, and returns the product.

# Befunge-93, 20 bytes

&>:2%!#v_.@
^*3/2 <


Try it online!

& - take in input and add it to the stack
> - move right
: - duplicate the top of the stack
2 - add two to the stack
% - pop 2 and the input off the stack and put input%2 on the stack
! - logical not the top of the stack
# - jump over the next command
_ - horizontal if, if the top of the stack is 0 (i.e. input%2 was non zero) go
right, else go left

If Zero:
. - output the top of the stack
@ - end code

If Not Zero:
v - move down
< - move left
2 - add 2 the top of the stack
/ - pop top two, add var/2 to the stack
3 - add 3 to stack
* - pop top two, add var*3 to the stack
^ - move up
> - move right (and start to loop)


# Perl 6, 14 bytes

{1.5**.lsb*$_}  lsb returns the position of the least-significant bit, counted from the right. That is, how many trailing zeroes in the binary representation, which is the same as the number of factors of 2. So raise 3/2 to that power and we're done. say {$_*1.5**.lsb}(24);
> 81


# Pyke, 5 bytes

P1.|B


Try it online!

# Actually, 9 bytes

w⌠i1|ⁿ⌡Mπ


Try it online!

Explanation:

w⌠i1|ⁿ⌡Mπ
w          factor into [prime, exponent] pairs
⌠i1|ⁿ⌡M   for each pair:
i          flatten
1|        prime | 1 (bitwise OR)
ⁿ       raise to exponent
π  product
`