Términos de la secuencia EKG

13

Introducción

La secuencia EKG comienza con 1 y 2, luego la regla es que el siguiente término es el entero positivo más pequeño que aún no está en la secuencia y cuyo factor común con el último término es mayor que 1 (no son coprimos).

Los primeros términos son:

1, 2, 4, 6, 3, 9, 12, 8, 10, 5, 15, ...

Se llama EKG porque la gráfica de sus términos es bastante similar a un EKG.

Es la secuencia A064413 en el OEIS .

Desafío

Debe escribir una función que tome un número entero n como entrada y produzca cuántos de los n primeros términos de la secuencia son mayores que n .

Como la regla de la secuencia comienza con el tercer término, el entero de entrada debe ser mayor o igual a 3. Por ejemplo, dada la entrada, 10la salida se 1debe a que el séptimo término es 12y ninguno de los otros diez primeros términos excede 10.

Casos de prueba

3 -> 1

10 -> 1

100 -> 9

1000 -> 70

Reglas

  • Para enteros inferiores a 3, la función puede generar 0 o un código de error.
  • No hay otras reglas particulares, excepto: es el código de golf, ¡cuanto más corto, mejor!
david
fuente
¿Podemos usar la indexación 0, 1siendo el término 0 de la secuencia y, por lo tanto, haciendo, por ejemplo, 15el décimo término, en lugar de 5?
Shaggy
@ Shaggy Creo que es justo usar esto como una forma matemática, pero en realidad cambiará el resultado de los casos de prueba y, de hecho, la función solicitada en sí misma. Por lo tanto, creo que no debería permitírselo. Lo siento.
David
oeis.org/A064413/graph - ¿OEIS puede escribir gráficos? Ordenado.
Urna mágica del pulpo

Respuestas:

7

Jalea , 20 19 18 bytes

S‘gṪ’ɗƇḟ¹Ṃṭ
1Ç¡>¹S

Este es un programa completo.

Pruébalo en línea!

Cómo funciona

1Ç¡>¹S       Main link. Argument: n (integer)

1            Set the return value to 1.
 Ç¡          Call the helper link n times.
   >¹        Compare the elements of the result with n.
     S       Take the sum, counting elements larger than n.


S‘gṪ’ɗƇḟ¹Ṃṭ  Helper link. Argument: A (array or 1)

S            Take the sum of A.
 ‘           Increment; add 1.
     ɗƇ      Drei comb; keep only elements k of [1, ..., sum(A)+1] for which the
             three links to the left return a truthy value.
  g              Take the GCD of k and all elements of A.
   Ṫ             Tail; extract the last GCD.
    ’            Decrement the result, mapping 1 to 0.
       ḟ¹    Filterfalse; remove the elements that occur in A.
         Ṃ   Take the minimum.
          ṭ  Tack; append the minimum to A.

Tenga en cuenta que la secuencia generada es [1,0,2,4,6,3,9,12,8,10,5,15,] . Dado que llamar al enlace auxiliar n veces genera una secuencia de longitud n+1 , prácticamente se ignora el 0 .

Dennis
fuente
6

Perl 6 , 66 63 59 58 bytes

-4 bytes gracias a Jo King

{sum (1,2,{+(1...all *gcd@_[*-1]>1,*∉@_)}...*)[^$_]X>$_}

Pruébalo en línea!

Demasiado lento en TIO para n = 1000.

nwellnhof
fuente
@JoKing Después de darme cuenta de que first &f,1..*se puede reescribir +(1...&f), su truco de unión ayudó después de todo.
nwellnhof
4

JavaScript (ES6), 107 106 105 bytes

f=(n,a=[2,1],k=3)=>a[n-1]?0:a.indexOf(k)+(C=(a,b)=>b?C(b,a%b):a>1)(k,a[0])?f(n,a,k+1):(k>n)+f(n,[k,...a])

Pruébalo en línea!

¿Cómo?

C

C = (a, b) => b ? C(b, a % b) : a > 1

un[2,1]un[0 0]

k0 0

a.indexOf(k) + C(k, a[0])

a.indexOf(k) es igual a:

  • -1kun
  • 0 0k
  • yo1

a.indexOf(k) + C(k, a[0])0 0kunk-1+trtumi=0 0

Arnauld
fuente
4

Haskell, 89 82 bytes

Editar: -7 bytes gracias a @ H.PWiz

f l=[n|n<-[3..],all(/=n)l,gcd(l!!0)n>1]!!0:l
g n=sum[1|x<-iterate f[2]!!(n-2),x>n]

Pruébalo en línea!

nimi
fuente
82 bytes
H.PWiz
@ H.PWiz: ah, eso es inteligente. ¡Gracias!
nimi
4

Casco , 16 bytes

#>¹↑¡§ḟȯ←⌋→`-Nḣ2

Pruébalo en línea!

Explicación

#>¹↑¡§ḟȯ←⌋→`-Nḣ2  Implicit input, say n=10
              ḣ2  Range to 2: [1,2]
    ¡             Construct an infinite list, adding new elements using this function:
                   Argument is list of numbers found so far, say L=[1,2,4]
             N     Natural numbers: [1,2,3,4,5,6,7...
           `-      Remove elements of L: K=[3,5,6,7...
      ḟ            Find first element of K that satisfies this:
                    Argument is a number in K, say 6
     §    →         Last element of L: 4
         ⌋          GCD: 2
       ȯ←           Decrement: 1
                    Implicitly: is it nonzero? Yes, so 6 is good.
                  Result is the EKG sequence: [1,2,4,6,3,9,12...
   ↑              Take the first n elements: [1,2,4,6,3,9,12,8,10,5]
#                 Count the number of those
 >¹               that are larger than n: 1
Zgarb
fuente
3

MATL , 29 bytes

qq:2:w"GE:yX-y0)yZdqg)1)h]G>z

Pruébalo en línea!

Explicación:

	#implicit input, n, say 10
qq:	#push 1:8
2:	#push [1 2]. Stack: {[1 .. 8], [1 2]}
w	#swap top two elements on stack
"	#begin for loop (do the following n-2 times):
 GE:	#push 1...20. Stack: {[1 2], [1..20]}
 y	#copy from below. Stack:{[1 2], [1..20], [1 2]}
 X-	#set difference. Stack: {[1 2], [3..20]}
 y0)	#copy last element from below. Stack:{[1 2], [3..20], 2}
 yZd	#copy from below and elementwise GCD. Stack:{[1 2], [3..20],[1,2,etc.]}
 qg)	#select those with gcd greater than 1. Stack:{[1 2], [4,6,etc.]}
 1)	#take first. Stack:{[1 2], 4}
 h	#horizontally concatenate. Stack:{[1 2 4]}
 ]	#end of for loop
G>z	#count those greater than input
	#implicit output of result
Giuseppe
fuente
¿puede explicar por qué duplica la entrada (con GE:)?
David
2
un(norte)2norteun(norte)norte2norte=1000while
3

APL (Dyalog Unicode) , SBCS de 39 bytes

-2 bytes gracias a ngn, -1 byte utilizando la verificación condicional adecuada.

{+/⍵<⍵⍴3{(1=⍺∨⊃⌽⍵)∨⍺∊⍵:⍵∇⍨⍺+1⋄⍵,⍺}⍣⍵⍳2}

Pruébalo en línea!

halcón vacío
fuente
pasa su propio argumento izquierdo a la función operando, por lo que no es necesario . Además, no se unirá con la cosa de la derecha, ya que comienza con una función ( ), por lo que no es necesario .
ngn
2

JavaScript, 93 91 87 bytes

Lanza un error de desbordamiento para 0o 1, salidas 0para 2.

n=>(g=x=>n-i?g[++x]|(h=(y,z)=>z?h(z,y%z):y)(x,c)<2?g(x):(g[c=x]=++i,x>n)+g(2):0)(i=c=2)

Pruébalo en línea

Lanudo
fuente
2

APL (NARS), caracteres 121, bytes 242

∇r←a w;i;j;v
r←w⋄→0×⍳w≤2⋄i←2⋄r←⍳2⋄v←1,1,(2×w)⍴0
j←¯1+v⍳0
j+←1⋄→3×⍳1=j⊃v⋄→3×⍳∼1<j∨i⊃r⋄r←r,j⋄i+←1⋄v[j]←1⋄→2×⍳w>i
r←+/w<r
∇

prueba en menos de un minuto aquí en tiempo de ejecución:

  a¨3 10 100 1000 2000
1 1 9 70 128 

Natural, no hay verificación de tipo y rango ...

RosLuP
fuente
1

Japt, 23 21 bytes

@_jX ªAøZ}f}gA=ì)Aè>U

Intentalo

@_jX ªAøZ}f}gA=ì)Aè>U
                          :Implicit input of integer U
             A            :10
               ì          :Digit array
              =           :Reassign to A
@          }g             :While the length of A < U+1, take the last element as X,
                          :pass it through the following function & push the result to A
 _       }f               :  Find the first integer Z >= 0 that returns falsey
  jX                      :    Is Z co-prime with X?
     ª                    :    OR
      AøZ                 :    Does A contain Z?
                )         :End loop
                 Aè>U     :Count the elements in A that are greater than U
Lanudo
fuente
1

Python 3 , 153 bytes

import math
def f(n):
 l=[1];c=0
 for _ in range(n-1):l+=[min(*range(2,n*4),key=lambda x:n*8if x in l or math.gcd(x,l[-1])<2else x)];c+=l[-1]>n
 return c

Pruébalo en línea! (Advertencia: toma ~ 30 segundos para evaluar)

Black Owl Kai
fuente