Remplacer deux par trois

36

Étant donné un entier positif n écrit un code pour prendre sa factorisation première et remplacer tous ses facteurs de 2avec 3.

Par exemple

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

C’est du donc l’objectif est de minimiser le nombre d’octets de votre réponse.

Cas de test

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
Assistant de blé
la source

Réponses:

63

Fractran , 3 octets

3/2

Fractran n'a littéralement qu'un seul élément intégré, mais il arrive à faire exactement ce que cette tâche demande. (C'est aussi Turing-complet, par lui-même.)

Le langage n'a pas vraiment de syntaxe standardisée ni d'interprète. Cet interprète (dans un commentaire sur un article de blog - c'est un langage très simple) acceptera la syntaxe indiquée ici. (Il existe d’autres interpréteurs Fractran avec d’autres syntaxes, par exemple, certains écriraient ce programme sous la forme 3 2, ou même en utilisant 3et 2en arguments de ligne de commande, ce qui donnerait un score de 0 + 3 octets. Je doute qu’il soit possible de faire mieux que 3 dans un fichier. interprète pré-existant, cependant.)

Explication

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

la source
10
Parler du bon outil pour le travail ..
Kevin Cruijssen
23
"Ne votez pas pour des solutions triviales qui utilisent uniquement une architecture intégrée simple." Eh bien, dans ce cas: savoir qu’il existe un langage "Fractran" qui n’a qu’un seul composant intégré et qui résout cette tâche spécifique est en soi impressionnant.
Stewie Griffin
3
Related SO code golf (pré-PPCG): Écrivez un interprète Fractran .
Hobbs
1
@AnderBiguri: Probablement à la recherche d'un langage complet de Turing très simple / facile à mettre en œuvre. Fractran est vraiment élégant comme le font les tarpits de Turing; la plupart ont beaucoup plus de bords bruts, de cas spéciaux ou de détails qui pourraient être modifiés sans faire une grande différence.
3
@AnderBiguri On dirait que cela est sorti de ses études sur la conjecture de Collatz; il a prouvé qu'une généralisation de Collatz est équivalente à Fractran et que Fractran est Turing-complete, donc Collatz généralisé est indécidable.
Hobbs
21

Python 2 , 28 octets

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

Essayez-le en ligne!

Divisez récursivement le nombre par 2 et multipliez le résultat par 3, tant que le nombre est pair. Les nombres impairs reviennent eux-mêmes.

32 octets alt:

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

Essayez-le en ligne . A une erreur de flottement. La constante est log_2(3)-1.

Utilise (n&-n)pour trouver le plus grand facteur de puissance de 2 n, les convertis 3**kà 2**ken l' élevant à la puissance log_2(3)-1.

Xnor
la source
Nice c'est ma solution exactement!
Wheat Wizard
@ WheatWizard Moi aussi, aha!
Graviton
18

05AB1E , 4 octets

Ò1~P

Essayez-le en ligne!

Comment ça marche

Ò     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.
Dennis
la source
Cela bat Jelly de 1 octet simplement parce que la factorisation n'est que d'un octet ici :(
HyperNeutrino
5
@HyperNeutrino: J'ai aussi remarqué cela: "Pourquoi Dennis utilise-t-il 05AB1E? Oh, algorithme identique, noms internes plus courts". Je devais donc aller chercher un langage où je pouvais le faire avec encore moins d'octets, en utilisant un ensemble encore plus approprié de fonctions intégrées.
14

Haskell, 24 23 octets

until odd$(*3).(`div`2)

La division par deux et multiplier par 3 jusqu'à astuce étrange dans Haskell.

Essayez-le en ligne!

Alternative avec une fonction lambda au lieu d'une fonction sans points et avec le même nombre d'octets:

odd`until`\x->div(x*3)2

Edit: @ ais523 a enregistré un octet dans la version originale et @ Ørjan Johansen dans la version alternative, les deux versions ont donc toujours la même longueur. Merci!

nimi
la source
3
La version lambda peut être abrégée odd`until`\x->div(x*3)2.
Ørjan Johansen
2
La version originale peut également être raccourcie d’un octet via l’utilisation de $pour remplacer une paire de parenthèses: Essayez-le en ligne!
@ ØrjanJohansen: ah bon! Merci.
Nimi
@ ais523: Comment aurais-je pu manquer celui-là, merci!
Nimi
2
Je pense que vous avez oublié de retirer une paire de ()la version lambda
CAD97
8

JavaScript (ES6), 19 octets

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

Alors que l’entrée est divisible par deux, multipliez-la par 1,5, ce qui équivaut à la division par 2 et à la multiplication par 3.

ETHproductions
la source
2
x*3/2 has the same bytecount
Leaky Nun
1
f= is usally not needed for js.
Christoph
3
@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
@ETHproductions Uhm ... of course ! I missed that. Is there any meta on what the calling code exactly looks like?
Christoph
2
@Christoph Here is the relevant meta post.
ETHproductions
8

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

0 '
la source
> Coming soon ...
Wheat Wizard
7

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.

Greg Martin
la source
Would x_?EvenQ work instead of x_/;EvenQ@x?
Not a tree
1
You're totally right, thanks!
Greg Martin
6

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
Emigna
la source
2
ÒDÈ+P should save a byte
Adnan
@Adnan: Thanks!
Emigna
6

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.
Martin Ender
la source
1
Your obsession is officially confirmed.
Leaky Nun
4

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!

HyperNeutrino
la source
2
Hint: 2 is both the only even and the smallest prime number.
Dennis
@Dennis I see. Yes, got it now. Thanks! :)
HyperNeutrino
Congratulations on learning Jelly.
Leaky Nun
@LeakyNun Thanks! And thanks for teaching it to me. :)
HyperNeutrino
Congrats on this answer!
Erik the Outgolfer
4

Pyth - 14 10 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

Maria
la source
Interesting approach - too bad it's not as short as the existing Pyth solution.
Esolanging Fruit
@Challenger5 I'm not seeing any other Pyth solution here.
Maria
1
Oh, OK then. It's a more interesting approach than the typical one for this challenge.
Esolanging Fruit
4

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:

Ungolfed

Approximate Memory Layout

enter image description here

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
Manfred Radlwimmer
la source
1
Welcome to PPCG! :)
Martin Ender
@MartinEnder Thanks, awesome language btw. :)
Manfred Radlwimmer
1
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
@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
3

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
Leaky Nun
la source
2

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

Adám
la source
I thought you find [: disgusting.
Leaky Nun
@LeakyNun I do, but I wasn't as clever as Conor O'Brien.
Adám
2

J, 15 12 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
Conor O'Brien
la source
Huh, you switched algorithm while I was writing up mine. Now we use the same.
Adám
@Adám Oh, haha. Nice answer! I couldn't resist the opportunity to use roll here. :)
Conor O'Brien
Actually I might be able to save some more bytes...edit saved some :D
Conor O'Brien
Funny you call it Roll, I call it Under. Hope to get it into APL soon.
Adám
@Adám Haha it's actually called under. I got the terms confused
Conor O'Brien
2

Pyth, 9 bytes

Integer output \o/

*F+1.|R1P

Test suite.

How it works

*F+1.|R1P
        P   prime factorization
    .|R1    bitwise OR each element with 1
*F+1        product
Leaky Nun
la source
2

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
Luke
la source
Hah, JS is tied with Japt. A sure sign there's a much shorter solution ;-)
ETHproductions
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
Thanks, though the recursive solution really is the shortest.
Luke
Nice one! I think you can do k m_w3Ã× to save a byte. Also, m_ can be shortened to ®.
Oliver
2

PHP, 36 Bytes

for($a=$argn;$a%2<1;)$a*=3/2;echo$a;

Try it online!

Jörg Hülsermann
la source
1
for($a=$argn;!1&$a;)$a*=3/2;echo$a; renaming $argn saves a single byte.
Christoph
2

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
Esolanging Fruit
la source
2

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.

Jo King
la source
Well damn, I didn't think of that
Manfred Radlwimmer
1
@ManfredRadlwimmer Don't worry, coding anything in Hexagony is an achievement in itself
Jo King
1

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
ETHproductions
la source
1

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.

JAD
la source
1

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)
bwillsh
la source
17 bytes
Jo King
1

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
Phil H
la source
0

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
Mego
la source