Calcola i numeri MU


19

I primi due numeri MU sono 2 e 3. Ogni altro numero MU è il numero più piccolo non ancora apparso che può essere espresso come il prodotto di due precedenti numeri MU distinti esattamente in un modo.

Ecco i primi 10

2, 3, 6, 12, 18, 24, 48, 54, 96, 162

Compito

Dato un numero di calcolare positivo e l'uscita n ° MU-numero.

Questa è una competizione di , quindi dovresti mirare a rendere il tuo codice sorgente il più piccolo possibile.

OEIS A007335


1
0-indicizzazione o 1-indicizzazione?
HyperNeutrino,

1
@HyperNeutrino O va bene.
Wheat Wizard

2
Qualche idea sul perché questi siano chiamati numeri MU? (Indovina selvaggia: moltiplicazione unica?)

Risposte:


5

Pyth, 22 21 byte

@u+Gfq2l@GcLTGheGQhB2

Provalo online. Suite di test.

0-indicizzati.

Spiegazione

@u+Gfq2l@GcLTGheGQhB2Q    Implicitly append Q and read+eval input to it.
                  hB2     Take the list [2, 2 + 1].
 u               Q        Put the list in G and apply this Q times:
               eG           Get last number in G.
              h             Add one.
    f                       Starting from that, find the first T such that:
          cLTG                Divide T by each of the numbers in G.
        @G                    Find the quotients that are also in G.
       l                      Get the number of such quotients.
     q2                       Check that it equals 2.
  +G                        Append that T to G.
@                    Q    Get the Q'th number in G.

Il @segno sull'ultima riga non è allineato. Non riesco a effettuare una modifica suggerita, poiché si tratta di una modifica di 2 caratteri.
user2357112 supporta Monica il

@ user2357112 Risolto.
PurkkaKoodari,

4

Haskell, 80 77 byte

l#(a:b)|[x]<-[a|i<-l,j<-l,i<j,i*j==a]=a:(a:l)#b|1<2=l#b
((2:3:[2,3]#[4..])!!)

Provalo online!

Come funziona

2:3:             -- start the list with 2 and 3 and append a call to # with
    [2,3]        -- the list so far and
         #[4..]  -- list of candidate elements

l # (a:b)        -- l -> list so far, a -> next candidate element, b -> rest c.el.
  | [x]<-[...]   -- if the list [...] is a singleton list
    =a:(a:l#b) -- the result is a followed by a recursive call with l extended
                    by a and b
  | 1<2=l#b      -- if it's not a singleton list, drop a and retry with b

                 -- the [...] list is
 [ i<-l,j<-l,    -- loop i through l and j through l and whenever   
       i<j,      -- i<j and
       i*j==a]   -- i*j==a
  a|             -- add a to the list              

3

Gelatina , 22 byte

ŒcP€ḟ⁸ṢŒgLÞḢḢṭ
2,3Ç¡ị@

Un collegamento monadico, 1 indicizzato.

Provalo online!

Come?

ŒcP€ḟ⁸ṢŒgLÞḢḢṭ - Link 1, add the next number: list, a  e.g. [2,3,6,12,18,24]
Œc             - unordered pairs                            [[2,3],[2,6],[2,12],[2,18],[2,24],[3,6],[3,12],[3,18],[3,24],[6,12],[6,18],[6,24],[12,18],[12,24],[18,24]]
  P€           - product of €ach                            [6,12,24,36,48,18,36,54,72,72,108,144,216,288,432]
     ⁸         - chain's left argument, a                   [2,3,6,12,18,24]
    ḟ          - filter discard                             [36,48,36,54,72,72,108,144,216,288,432]
      Ṣ        - sort                                       [36,36,48,54,72,72,108,144,216,288,432]
       Œg      - group runs of equal elements               [[36,36],[48],[54],[72,72],[108],[144],[216],[288],[432]]
          Þ    - sort by:
         L     -   length                                   [[48],[54],[108],[144],[216],[288],[432],[36,36],[72,72]]
           Ḣ   - head                                       [48]
            Ḣ  - head                                       48
             ṭ - tack to a                                  [2,3,6,12,18,24,48]

2,3Ç¡ị@ - Link: number, i                              e.g. 7
2,3     - literal [2,3]                                     [2,3]
    ¡   - repeat i times:
   Ç    -   call last link (1) as a monad                   [2,3,6,12,18,24,48,54,96]
     ị@ - index into with swapped @rguments (with i)        48

3

R , 127 118 111 108 105 100 98 90 byte

8 byte grazie a Giuseppe.

r=3:2;for(i in 1:scan())r=c(min((g=(r%o%r)[i:-1<i])[colSums(g%o%g==g*g)+g%in%r<3]),r);r[3]

Provalo online!


Mi ci è voluto un'eternità per rendermi conto che <ha una precedenza inferiore rispetto a quella +che non riuscivo a capire cosa diavolo +g%in%r<3stesse facendo, e mentre lo facevo, hai giocato a golf le due parti che stavo per suggerire ... +1
Giuseppe

@Giuseppe Ho appena iniziato a studiare R oggi ... piacere di conoscere un giocatore di golf R decente.
Leaky Nun,

Stavo per dirti lo stesso .............
Giuseppe,

Ah, un'altra cosa, puoi usare n=scan()invece di una definizione di funzione per leggere da stdin; che ti porterà sotto i 100 anni
Giuseppe,

Errore di input:0
Rift

2

CJam (32 byte)

4,{_2m*{~>},::*1$-$e`$0=|}qi*-2=

Demo online con indicizzazione 0.

Non sono sicuro che ci sia molto da fare oltre a una banale traduzione delle specifiche con una sola eccezione: partendo da un elenco di [0 1 2 3](anziché [2, 3]) salvo immediatamente un byte sull'inizializzazione e altri due potendo fare 0=|(aggiungendo solo il nuovo elemento perché la sua frequenza è 1ed è già nell'elenco), ma non introdurre alcun elemento falso perché per tutti xnell'elenco 0*xe 1*xsono già nell'elenco.


2

Python 2 , 127 118 byte

n=input()
l=[2,3]
exec't=sorted(x*y for i,x in enumerate(l)for y in l[i+1:]);l+=min(t,key=(l+t).count),;'*n
print l[n]

Provalo online!


1

Mathematica, 154 byte

semplice modifica del codice trovato sul link oeis

(s={2,3};Do[n=Select[Split@Sort@Flatten@Table[s[[j]]s[[k]],{j,Length@s},{k,j+1,Length@s}],#[[1]]>s[[-1]]&&Length@#==1&][[1,1]];AppendTo[s,n],{#}];s[[#]])&

1

PHP , 130 byte

0-indicizzato

for($r=[2,3];!$r[$argn];$r[]=$l=min($m)/2){$m=[];foreach($r as$x)foreach($r as$y)($p=$x*$y)<=$l|$y==$x?:$m[$p]+=$p;}echo$r[$argn];

Provalo online!

allargato

for($r=[2,3];!$r[$argn]; #set the first to items and loop till search item exists
$r[]=$l=min($m)/2){ # add the half of the minimum of found values to the result array
  $m=[]; # start with empty array
  foreach($r as$x) # loop through result array
    foreach($r as$y) # loop through result array
      ($p=$x*$y)<=$l|$y==$x? # if product is greater as last value and we do multiple two distinct values
        :$m[$p]+=$p; # add 2 times or more the product to array so we drop 36 cause it will be 144  
}
echo$r[$argn]; # Output 

PHP , 159 byte

0-indicizzato

for($r=[2,3];!$r[$argn];$r[]=$l=min(array_diff_key($m,$d))){$d=$m=[];foreach($r as$x)foreach($r as$y)$x<$y?${dm[$m[$p=$x*$y]<1&$p>$l]}[$p]=$p:0;}echo$r[$argn];

Provalo online!

PHP , 161 byte

0-indicizzato

for($r=[2,3];!$r[$argn];$r[]=$l=min(array_diff($m,$d))){$d=$m=[];foreach($r as$x)foreach($r as$y)$x<$y?${dm[!in_array($p=$x*$y,$m)&$p>$l]}[]=$p:0;}echo$r[$argn];

Provalo online!


1

Mathematica, 140 byte

(t=1;s={2,3};While[t<#,s=AppendTo[s,Sort[Select[First/@Select[Tally[Times@@@Permutations[s,{2}]],#[[2]]==2&],#>Last@s&]][[1]]];t++];s[[#]])&

1

MATL , 25 byte

3:i:"t&*9B#u2=)yX-X<h]2_)

Provalo online!

Spiegazione

3:     % Push [1 2 3]. Initial array of MU numbers, to be extended with more numbers
i:     % Input n. Push [1 2 ... n]
"      % Do this n times
  t    %   Duplicate array of MU numbers so far
  &*   %   Matrix of pair-wise products
  9B   %   Push 9 in binary, that is, [1 0 0 1]
  #    %   Specify that next function will produce its first and fourth ouputs
  u    %   Unique: pushes unique entries (first output) and their counts (fourth)
  2=   %   True for counts that equal 2
  )    %   Keep only unique entries with count 2
  y    %   Duplicate (from below) array of MU numbers so far
  X-   %   Set difference
  X<   %   Minimum. This is the new MU number
  h    %   Concatenate vertically horizontally to extend the array
]      % End
2_     % Push 2 negated, that is, -2
)      % Get entry at position -2, that is, third-last. Implicitly display

1

Perl 6 , 96 byte

{(2,3,{first *∉@_,@_.combinations(2).classify({[*]
$_}).grep(*.value==1)».key.sort}...*)[$_]}

Provalo online!

  • 2, 3, { ... } ... *è una sequenza infinita in cui ogni elemento che inizia con il terzo viene calcolato dal blocco di codice delimitato da parentesi graffe. Poiché il blocco di codice accetta i suoi argomenti tramite l' @_array slurpy , riceve l'intera sequenza corrente in quell'array.
  • @_.combinations(2)è una sequenza di tutte le combinazioni di 2 elementi di @_.
  • .classify({ [*] $_ }) classifica ogni 2 tuple in base al suo prodotto, producendo un hash in cui i prodotti sono le chiavi e i valori sono l'elenco delle 2 tuple che hanno quel prodotto.
  • .grep(*.value == 1) seleziona quelle coppie chiave-valore dall'hash in cui il valore (ovvero l'elenco delle coppie che hanno quella chiave come prodotto) ha una dimensione di 1.
  • ».keyseleziona solo i tasti di ciascuna coppia. Questo è l'elenco dei prodotti che derivano da una sola combinazione di fattori della sequenza corrente.
  • .sort ordina i prodotti numericamente.
  • first * ∉ @_, ... trova il primo di quei prodotti che non è già apparso nella sequenza.

1

JavaScript (ES6), 119 118 117 byte

Una funzione ricorsiva che accetta un indice basato su 0.

f=(n,a=[2,m=3])=>a[n]||a.map(c=>a.map(d=>c<d&(d*=c)>m?b[d]=b[d]/0||d:0),b=[])|f(n,a.push(m=b.sort((a,b)=>a-b)[0])&&a)

Come?

Ad ogni iterazione di f () , usiamo l'ultimo termine m della sequenza e un array inizialmente vuoto b per identificare il termine successivo. Per ogni prodotto d> m di due precedenti numeri MU distinti, facciamo:

b[d] = b[d] / 0 || d

e quindi mantenere il valore minimo di b .

L'espressione sopra è valutata come segue:

b[d]               | b[d] / 0  | b[d] / 0 || d
-------------------+-----------+--------------
undefined          | NaN       | d
already equal to d | +Infinity | +Infinity
+Infinity          | +Infinity | +Infinity

Ciò garantisce che i prodotti che possono essere espressi in più di un modo non saranno mai selezionati.

Formattato e commentato

f = (n, a = [2, m = 3]) =>           // given: n = input, a[] = MU array, m = last term
  a[n] ||                            // if a[n] is defined, return it
  a.map(c =>                         // else for each value c in a[]:
    a.map(d =>                       //   and for each value d in a[]:
      c < d &                        //     if c is less than d and
      (d *= c) > m ?                 //     d = d * c is greater than m:
        b[d] = b[d] / 0 || d         //       b[d] = either d or +Infinity (see 'How?')
      :                              //     else:
        0                            //       do nothing
    ),                               //   end of inner map()
    b = []                           //   initialization of b[]
  ) |                                // end of outer map()
  f(                                 // do a recursive call:
    n,                               //   - with n
    a.push(                          //   - push in a[]:
      m = b.sort((a, b) => a - b)[0] //     m = minimum value of b[]
    ) && a                           //     and use a[] as the 2nd parameter
  )                                  // end of recursive call

dimostrazione


0

Haskell , 117 115 113 byte

n x=[a*b|[a,b]<-mapM id[1:x,x]]
d x=minimum[a|a<-n x,2==sum[1|b<-n x,b==a]]:x
l x|x<3=x+1:[2]|1>0=d$l$x-1
(!!0).l

Provalo online!


La prima riga può essere scritta come un linguaggio utile per il prodotto cartesiano dell'operatore:n x=(*)<$>x<*>1:x
xnor

0

Python 3 2 , 167 139 136 133 123 121 120 118 byte

a=[2,3];exec'p=[x*y for x in a for y in a if x-y];a+=min(q for q in p if p.count(q)+(q in a)<3),;'*input();print a[-2]

Provalo online!


Grazie a @ Mr.Xcoder e @LeakyNun per i miglioramenti!


159 byte , semplicemente rimuovendo spazi e parentesi non necessari.
Mr. Xcoder,

@ Mr.Xcoder Grazie per i miglioramenti. Non sono sicuro che il passaggio p.count(q)==1a p.count(q)>0sia valido, perché è il codice che garantisce la condizione "esattamente in un modo" della sfida.
Chase Vogeli,

p.count(q)-~(q in a)<=3è equivalente ap.count(q)+(q in a)<3
Leaky Nun il

@LeakyNun grazie!
Chase Vogeli,
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.