# 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.. Commented May 5, 2017 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. Commented May 5, 2017 at 8:51
• @Pandya: Some Fractran implementations use prime factorization internally (as an optimization), but they don't have to; the language operates on factors, not prime factors. (It just happens that 2 and 3 are prime.)
– user62131
Commented May 5, 2017 at 12:23
• Related SO code golf (pre-PPCG): Write a Fractran interpreter. Commented May 8, 2017 at 5:29
• @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. Commented May 8, 2017 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! Commented May 4, 2017 at 21:50
• @WheatWizard Me as well, aha! Commented May 5, 2017 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 :( Commented May 4, 2017 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
Commented May 5, 2017 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. Commented May 4, 2017 at 23:55 • The original version can also be shortened one byte via using $ to replace a pair of parentheses: Try it online!
– user62131
Commented May 5, 2017 at 3:39
• @ØrjanJohansen: ah, nice! Thanks.
– nimi
Commented May 5, 2017 at 5:04
• @ais523: How could I have missed that one, Thanks!
– nimi
Commented May 5, 2017 at 5:05
• I think you forgot to remove a pair of () from the lambda version Commented May 5, 2017 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 Commented May 5, 2017 at 3:42
• f= is usally not needed for js. Commented May 5, 2017 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. Commented May 5, 2017 at 11:45
• @ETHproductions Uhm ... of course ! I missed that. Is there any meta on what the calling code exactly looks like? Commented May 5, 2017 at 12:17
• @Christoph Here is the relevant meta post. Commented May 5, 2017 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.

### More detailed explanation eventually...

• > Coming soon ... Commented Dec 23, 2017 at 22:38

# 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? Commented May 5, 2017 at 3:25
• You're totally right, thanks! Commented May 5, 2017 at 4:23

# 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


# Lean, 13982 71 bytes

11 bytes saved by ovs.

import data.nat.prime
open list
λx,prod$map(λp,p+1-p%2)$nat.factors x


Try it online!

I'm really new to lean so, this answer is probably really inefficient in ways I don't yet know. But it works.

We get a list of factors with nat.factors replace 2s with threes using a map and roll it back up with list.prod.

• p+1-p%2 seems to work instead of the conditional expression.
– ovs
Commented Oct 6, 2021 at 11:05
• @ovs Nice. It's tough to tell what library functions there are and what they are named. Commented Oct 6, 2021 at 11:11

# 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 Commented May 4, 2017 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 Commented May 4, 2017 at 22:28 # 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! ## 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. Commented May 5, 2017 at 3:38 # 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! :) Commented Mar 23, 2018 at 11:12 • @MartinEnder Thanks, awesome language btw. :) Commented Mar 23, 2018 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.) Commented Mar 23, 2018 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 ^^ Commented Mar 23, 2018 at 11:35 # 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. Commented May 4, 2017 at 22:15 • @Dennis I see. Yes, got it now. Thanks! :) Commented May 4, 2017 at 23:42 • Congratulations on learning Jelly. Commented May 5, 2017 at 3:49 • @LeakyNun Thanks! And thanks for teaching it to me. :) Commented May 5, 2017 at 3:50 • Congrats on this answer! Commented May 7, 2017 at 11:08 # 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 Commented May 5, 2017 at 10:27 # 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 Commented Mar 23, 2018 at 12:04 • @ManfredRadlwimmer Don't worry, coding anything in Hexagony is an achievement in itself – Jo King Commented Mar 23, 2018 at 12:28 # Retina, 23 bytes .+$*
+^(1+)\1&$1 1  Try it online! Link is to test suite that runs automatically runs all inputs from 1 to 29. Explanation: .+$*


Convert to unary.

+^(1+)\1&$1  While the value is even, multiply it by 3/2. 1  Convert to decimal. Note that any FRACTRAN program is trivially convertible to a Retina program with unary I/O. The fraction itself is converted into a match for a string that appears an exact number of times given by the denominator, and the substitution is then $1 repeated a number of times given by the numerator, although if this is greater than the denominator then $& can be used to golf down the code length. It then remains to loop each fraction back to the start of the script, so that the earliest possible fraction is always the next to be substituted. In the case of a single fraction no group is required of course. # 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. Commented May 5, 2017 at 2:31 • @Challenger5 I'm not seeing any other Pyth solution here. Commented May 5, 2017 at 4:25 • Oh, OK then. It's a more interesting approach than the typical one for this challenge. Commented May 5, 2017 at 4:27 # Risky, 9 bytes *\?+0+0+0__?\?+?:2  Try it online! # BQN (CBQN), 30 bytes {0=2|𝕩?3×𝕊𝕩÷2;𝕩} Attempt This Online! # 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. Commented May 5, 2017 at 3:39 • @LeakyNun I do, but I wasn't as clever as Conor O'Brien. – Adám Commented May 5, 2017 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 Commented May 4, 2017 at 22:24 • @Adám Oh, haha. Nice answer! I couldn't resist the opportunity to use roll here. :) Commented May 4, 2017 at 22:26 • Actually I might be able to save some more bytes...edit saved some :D Commented May 4, 2017 at 22:27 • Funny you call it Roll, I call it Under. Hope to get it into APL soon. – Adám Commented May 4, 2017 at 22:28 • @Adám Haha it's actually called under. I got the terms confused Commented May 4, 2017 at 22:29 # 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. Commented May 5, 2017 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


# 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


# 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


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

# 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 ;-) Commented May 4, 2017 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). Commented May 4, 2017 at 21:59
• Thanks, though the recursive solution really is the shortest.
– Luke
Commented May 4, 2017 at 22:05
• Nice one! I think you can do k m_w3Ã× to save a byte. Also, m_ can be shortened to ®. Commented May 5, 2017 at 0:43