Gere números n-ários


34

Um número secundário é um número inteiro positivo cujos fatores primos (sem multiplicidade) são todos iguais ou inferiores à sua raiz quadrada. 4é um número secundário, porque seu único fator primo é 2, que é igual a sua raiz quadrada. No entanto, 15não é um número secundário, porque tem 5como fator primordial, maior que sua raiz quadrada ( ~ 3.9). Como todos os números primos têm como fatores primos, nenhum número primo é um número secundário. Os primeiros números secundários são os seguintes:

1, 4, 8, 9, 12, 16, 18, 24, 25, 27, 30, 32, 36, 40, 45, 48, 49, 50, 54, 56

Um número terciário é definido da mesma forma, exceto que todos os fatores primos devem ser menores ou iguais à raiz do cubo. Os primeiros números terciários são os seguintes:

1, 8, 16, 27, 32, 36, 48, 54, 64, 72, 81, 96, 108, 125, 128, 135, 144, 150, 160, 162

Em geral, um número n-ário é aquele cujos fatores primos são todos iguais ou inferiores à sua n-ésima raiz. Assim, um número inteiro positivo x é um nnúmero -ar se cada um de seus fatores primos p satisfizer pnx . Assim, os números primários são todos números inteiros positivos (todos os fatores primos menores ou iguais a eles mesmos), os números quartenários têm todos os seus fatores primos menores ou iguais à sua quarta raiz e assim por diante.

O desafio

Dados inteiros ke ncomo entradas, imprima o número kth n-ary. kpode ser zero ou um indexado (sua escolha) e nsempre será positivo.

Exemplos

Estes são os 20 primeiros elementos em cada sequência, com números de até 10 árias:

Primary: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20
Secondary: 1, 4, 8, 9, 12, 16, 18, 24, 25, 27, 30, 32, 36, 40, 45, 48, 49, 50, 54, 56
Tertiary: 1, 8, 16, 27, 32, 36, 48, 54, 64, 72, 81, 96, 108, 125, 128, 135, 144, 150, 160, 162
Quarternary: 1, 16, 32, 64, 81, 96, 108, 128, 144, 162, 192, 216, 243, 256, 288, 324, 384, 432, 486, 512
5-ary: 1, 32, 64, 128, 243, 256, 288, 324, 384, 432, 486, 512, 576, 648, 729, 768, 864, 972, 1024, 1152
6-ary: 1, 64, 128, 256, 512, 729, 768, 864, 972, 1024, 1152, 1296, 1458, 1536, 1728, 1944, 2048, 2187, 2304, 2592
7-ary: 1, 128, 256, 512, 1024, 2048, 2187, 2304, 2592, 2916, 3072, 3456, 3888, 4096, 4374, 4608, 5184, 5832, 6144, 6561
8-ary: 1, 256, 512, 1024, 2048, 4096, 6561, 6912, 7776, 8192, 8748, 9216, 10368, 11664, 12288, 13122, 13824, 15552, 16384, 17496
9-ary: 1, 512, 1024, 2048, 4096, 8192, 16384, 19683, 20736, 23328, 24576, 26244, 27648, 31104, 32768, 34992, 36864, 39366, 41472, 46656
10-ary: 1, 1024, 2048, 4096, 8192, 16384, 32768, 59049, 62208, 65536, 69984, 73728, 78732, 82944, 93312, 98304, 104976, 110592, 118098, 124416

Respostas:


10

Gelatina , 12 bytes

Æf*³<‘Ạ
1Ç#Ṫ

Leva n e k (um indexado) como argumentos da linha de comando.

Experimente online!

Como funciona

1Ç#Ṫ     Main link. Left argument: n. Right argument: k

1        Set the return value to 1.
 Ç#      Execute the helper link above for r = 1, 2, 3, ... until k of them return
         a truthy value. Yield the list of all k matches.
   Ṫ     Tail; extract the last match.


Æf*³<‘Ạ  Helper link. Argument: r

Æf       Compute all prime factors of r.
  *³     Elevate them to the n-th power.
    <‘   Compare all powers with r + 1.
      Ạ  All; return 1 if all comparisons were true, 0 if one or more were not.

Aqui não há economia de bytes, mas eu ainda ficaria satisfeito, ÆfṪ*³<‘pois sabemos que, se algum fator falsificar, o da direita será.
Jonathan Allan

6

Braquilog , 21 bytes

:[1]cyt
,1|,.$ph:?^<=

Experimente online!

Esta resposta é um indexada.

Explicação

Input: [N:K]

:[1]cy              Retrieve the first K valid outputs of the predicate below with N as input
      t             Output is the last one

,1                  Output = 1
  |                 Or
   ,.$ph            Take the biggest prime factor of the Output
        :?^<=       Its Nth power is less than the Output

6

JavaScript (ES7), 95 90 bytes

Razoavelmente rápido, mas infelizmente limitado pelo número máximo de recursões.

f=(k,n,i=1)=>(F=(i,d)=>i-1?d>1?i%d?F(i,d-1):F(i/d,x):1:--k)(i,x=++i**(1/n)|0)?f(k,n,i):i-1

Como funciona

Em vez de fatorar um número inteiro i e verificar se todos os seus fatores primos são menores ou iguais a x = piso (i 1 / n ) , tentamos validar a última hipótese diretamente. Esse é o objetivo da função interna F () :

F = (i, d) =>         // given an integer i and a divisor d:
  i - 1 ?             //   if the initial integer is not yet fully factored
    d > 1 ?           //     if d is still a valid candidate
      i % d ?         //       if d is not a divisor of i
        F(i, d - 1)   //         try again with d-1 
      :               //       else
        F(i / d, x)   //         try to factor i/d
    :                 //     else
      1               //       failed: yield 1
  :                   //   else
    --k               //     success: decrement k

Verificamos se algum número inteiro d em [2 ... i 1 / n ] divide i . Caso contrário, a suposição não é válida e retornamos 1 . Se sim, repetimos recursivamente o processo em i = i / d até que ele falhe ou o número inteiro inicial seja totalmente fatorado ( i == 1 ); nesse caso, decrementamos k . Por sua vez, a função externa f () é chamada recursivamente até k == 0 .

Nota: Devido a erros de arredondamento de ponto flutuante, como 125**(1/3) == 4.9999…, o valor calculado real de x é floor ((i + 1) 1 / n ) .

Demo

(Aqui com uma versão ES6 de 97 bytes para uma melhor compatibilidade.)


6

JavaScript (ES7), 93 79 bytes

f=(k,n,g=(i,j=2)=>i<2?--k?g(++m):m:j**n>m?g(++m):i%j?g(i,j+1):g(i/j,j))=>g(m=1)

Eu não conseguia entender a resposta de Arnauld, então escrevi a minha e, convenientemente, ela veio com dois bytes a menos. Editar: salvou 14 bytes com a ajuda de @ETHproductions. Ungolfed:

function ary(k, n) {
    for (var c = 1;; c++) {
        var m = c;
        for (var i = 2; m > 1 && i ** n <= c; i++)
            while (m % i == 0) m /= i;
        if (m == 1 && --k == 0) return c;
    }
}

Curiosamente, o meu tinha exatamente 93 bytes antes de eu perceber um bug e decidir avaliar em ++i**(1/n)vez de i**(1/n)por causa de erros de arredondamento de ponto flutuante, como 125**(1/3) == 4.999.... (O jeito que está escrito, eu acho que o seu código não é afetado por isso.)
Arnauld

@ETHproductions Na verdade, lembrei-me de incluí-lo na contagem de bytes, eu só esqueceu de incluí-lo na resposta ...
Neil

@ETHproductions Parece funcionar, mas mudei a tarefa para mcortar mais dois bytes.
214 Neil

5

Haskell, 86 bytes

m#n=(0:1:filter(\k->last[n|n<-[2..k],all((>0).rem n)[2..n-1],k`rem`n<1]^n<=k)[2..])!!m

Explicação:

( %%%%denota o código da linha acima)

    [n|n<-[2..k],all((>0).rem n)[2..n-1],k`rem`n<1]  -- generates all prime factors of k
    last%%%%^n<=k                                    -- checks whether k is n-ary
    (0:1:filter(\k->%%%%)[2..])!!m                   -- generates all n-ary nubmers and picks the m-th
     m#n=%%%%                                        -- assignment to the function #

filtercom um lambda raramente compensa, uma compreensão da lista geralmente é mais curta: m#n=(0:1:[k|k<-[2..],last[n|n<-[2..k],all((>0).rem n)[2..n-1],krem n<1]^n<=k])!!m.
N /

Ah, você também pode omitir o 0:, porque a indexação pode ser baseada em 0.
nimi

... ainda melhor: m#n=[k|k<-[1..],last[n|n<-[1..k],all((>0).rem n)[2..n-1],kremn<1]^n<=k]!!m
nimi

3

Pitão, 13 bytes

e.f.AgL@ZQPZE

Experimente online.

Funciona realmente como a solução Jelly.

e.f.AgL@ZQPZE
                 Implicit: read n into Q.
            E    Read k.
 .f              Find the first k integers >= 1 for which
   .A            all
          P      prime factors of
           Z     the number
     gL          are at most
         Q       the n'th
       @         root of
        Z        the number.
e                Take the last one.

3

Perl 6, 88 bytes

->\k,\n{sub f(\n,\d){n-1??n%%d??f n/d,d!!f n,d+1!!d};(1,|grep {$_>=f($_,2)**n},2..*)[k]}

Minha percepção acidental é que você não precisa analisar todos os fatores n, apenas o maior, que é a função internaf calcula. Infelizmente, explode a pilha com entradas maiores.

A robustez pode ser aprimorada adicionando um teste de primalidade, usando o is-primemétodo interno do Ints, a um custo de vários outros caracteres.


3

Casca , 10 bytes

!fS≤ȯ^⁰→pN

Experimente online!

Explicação

Levei um tempo para descobrir usando on a lista vazia retornos 1em vez de -Infpara que as folhas 1na lista (caso contrário, que custaria 2 bytes para preceder-lo novamente):

!fS≤(^⁰→p)N  -- input n as ⁰ and k implicit, for example: 4 3
!f        N  -- filter the natural numbers by the following predicate (example on 16):
  S≤(    )   --   is the following less than the element (16) itself?
        p    --   ..prime factors (in increasing order): [2]
       →     --   ..last element/maximum: 2
     ^⁰      --   ..to the power of n: 16
             --   16 ≤ 16: yes
             -- [1,16,32,64,81..
!            -- get the k'th element: 32

2

R, 93 bytes

f=function(k,n){x='if'(k,f(k-1,n)+1,1);while(!all(numbers::primeFactors(x)<=x^(1/n)))x=x+1;x}

Indexado a zero.

É uma função recursiva que continua até encontrar o próximo número na fila. Usa para numbersempacotar para encontrar os principais fatores.


2

MATL, 21 bytes

x~`@YflG^@>~A+t2G<}x@

Esta solução usa indexação baseada em uma e as entradas são ne k, respectivamente.

Experimente Online!

Explicação

x       % Implicitly grab the first input and delete it
~       % Implicitly grab the second input and make it FALSE (0) (this is the counter)
`       % Beginning of the do-while loop
  @Yf   % Compute the prime factors of the current loop index
  1G^   % Raise them to the power of the first input
  @>    % Determine if each value in the array is greater than the current index
  ~A    % Yield a 0 if any of them were and a 1 if they weren't
  +     % Add this to the counter (increments only for positive cases)
  t2G<  % Determine if we have reached a length specified by the second input
}       % After we exit the loop (finally), ...
x@      % Delete the counter and push the current loop index to the stack
        % Implicitly display the result

Nice, utilizando ~ para redirecionar a segunda entrada :-)
Luis Mendo

1

Brachylog v2 , 16 bytes

{∧.ḋ,1⌉;?^≤}ᶠ⁽t

Experimente online!

Os meus agradecimentos à solução Jelly de Dennis por me fazer pensar na direção certa.

Explicação

Aqui está uma versão um pouco mais simples que é mais fácil de analisar:

↰₁ᶠ⁽t
∧.ḋ,1⌉;?^≤

Predicado auxiliar (linha 2): entrada é o expoente n , saída é irrestrita:

∧           Break implicit unification
 .ḋ         Get the prime factors of the output
   ,1       Append 1 (necessary because 1 has no prime factors and you can't take
            the max of an empty list)
     ⌉      Max (largest prime factor, or 1 if the output is 1)
      ;?    Pair that factor with the input (n)
        ^   Take factor to the power of n
         ≤  Verify that the result is less than or equal to the output

Predicado principal (linha 1): input é uma lista que contém o índice k (baseado em 1) e o expoente n ; a saída é irrestrita:

  ᶠ⁽   Find the first k outputs of
↰₁     calling the helper predicate with n as input
    t  Get the last (i.e. kth) one

0

APL (NARS), 53 caracteres, 106 bytes

r←a f w;c
c←0⋄r←1
→3×⍳∼∧/(πr)≤a√r⋄→0×⍳w≤c+←1
r+←1⋄→2

teste:

  1 f¨1..20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 
  2 f¨1..20
1 4 8 9 12 16 18 24 25 27 30 32 36 40 45 48 49 50 54 56 
  3 f¨1..20
1 8 16 27 32 36 48 54 64 72 81 96 108 125 128 135 144 150 160 162 
  4 f¨1..20
1 16 32 64 81 96 108 128 144 162 192 216 243 256 288 324 384 432 486 512 
  10 f¨1..20
1 1024 2048 4096 8192 16384 32768 59049 62208 65536 69984 73728 78732 82944 93312 98304 104976 110592 118098 124416 


0

Japt , 14 bytes

Toma ncomo a primeira entrada e k(indexada 1) como a segunda.

@_k e§Vq}aXÄ}g

Tente

Ao utilizar nosso site, você reconhece que leu e compreendeu nossa Política de Cookies e nossa Política de Privacidade.
Licensed under cc by-sa 3.0 with attribution required.