Piazze nelle piazze


10

Dato input di un numero intero positivo n, scrivere un programma che completa il seguente processo.

  • Trova il numero intero positivo più piccolo maggiore di nquello è un quadrato perfetto ed è la concatenazione di ne qualche altro numero. L'ordine delle cifre di nnon può essere modificato. Il numero concatenato su nper produrre un quadrato perfetto può essere chiamato r_1.
  • Se r_1non è un quadrato perfetto, ripetere il processo sopra descritto r_1come nuovo input per il processo. Ripeti fino a quando non r_kè un quadrato perfetto, indicato s.
  • Stampa il valore di sqrt(s).

L'input può essere preso in qualsiasi formato. Puoi presumere che nsia un numero intero positivo. Se uno r_kha uno zero iniziale (e r_k≠ 0), lo zero può essere ignorato.


Casi test

Ecco alcuni casi di test. Il processo dimostra i passaggi precedenti.

Input:   23
Process: 23, 2304, 4
Output:  2

Input:   10
Process: 10, 100, 0
Output:  0

Input:   1
Process: 1, 16, 6, 64, 4
Output:  2

Input:   5
Process: 5, 529, 29, 2916, 16
Output:  4

Input:   145
Process: 145, 145161, 161, 16129, 29, 2916, 16
Output:  4

Input:   1337
Process: 1337, 13373649, 3649, 36493681, 3681, 368102596, 2596, 25969216, 9216
Output:  96

Questo è il codice golf. Si applicano le regole standard. Vince la risposta più breve (in byte).

Risposte:


2

Pyth, 26 byte

LsI@b2 fy=sh.fys+QZ1\0)@Q2

Suite di test

L'output è come float. Se si desidera l'output come int, sarebbe 1 byte extra.

Spiegazione:

LsI@b2 fy=sh.fys+QZ1\0)s@Q2
                               Q = eval(input())
L                              def y(b): return
   @b2                         Square root of b
 sI                            Is an integer.
       f              )        Find the first positive integer T that satisfies
           h.f     1\0         Find the first digit string Z that satisfies
                +QZ            Concatenation of Q and Z
               s               Converted to an integer
              y                Is a pergect square.
          s                    Convert the string to an integer
         =                     Assign result to the next variable in the code, Q
        y                      Repeat until result is a perfect square
                               (The space) Discard return value
                        @Q2    Take square root of Q and print.

2

MATL , 35 44,0 byte

XK``x@2^tVKVXf1=a~]VKVnQ0h)UXKX^t1\

Provalo online!

XK        % implicit input: n. Copy to clipboard K
`         % do...while. Each iteration applies the algorithm
  `       %   do...while. Each iteration tests a candidate number
    x     %     delete top of stack
    @2^   %     iteration index squared
    t     %     duplicate
    V     %     convert to string                
    K     %     paste from clipboard K: n or r_k
    V     %     convert to string  
    Xf    %     find one string within another. Gives indices of starting matches, if any 
    1=a~  %     test if some of those indices is 1. If not: next iteration
  ]       %   end. We finish with a perfect square that begins with digits of n or r_k
  V       %   convert to string
  K       %   paste from clipboard K: n or r_k
  VnQ0h   %   index of rightmost characters, as determined by r_k
  )       %   keep those figures only
  U       %   convert to number. This is the new r_k
  XK      %   copy to clipboard K, to be used as input to algorithm again, if needed
  X^      %   square root
  1\      %   fractional part. If not zero: apply algorithm again
          % implitic do...while loop end
          % implicit display

2

Python 2, 98

i=input();d=o=9
while~-d:
 n=i;d=o+1;o=i=0
 while(n*d+i)**.5%1:i=-~i%d;d+=9*d*0**i
print'%d'%n**.5

Provalo online .


Dal momento che siamo in territorio abuso di galleggiante comunque ... while x**.5%1:forse?
Sp3000,

@ Sp3000 grazie! L'ho giocato un po 'di più adesso.
grc,

@Ampora solo il link ideone ha stampato il processo, ma ora l'ho cambiato.
grc,

1

Python, 200 198 178 byte

import math
def r(i):
 j=int(i**.5)+1
 while str(j*j)[:len(str(i))]!=str(i):j+=1
 return int(str(j*j)[len(str(i)):])
q=r(int(input()))
while math.sqrt(q)%1!=0:q=r(q)
print(q**.5)

È possibile salvare un buon numero di byte accorciando math.sqrta m.
Arcturus,

@Ampora Aww sì, salvato 2 byte
ThereGoesMySanity

1

Brachylog , 26 byte

{~a₀X√ℕ∧YcX∧Yh?∧Ybcℕ≜!}ⁱ√ℕ

Provalo online!

L'ultimo caso di test è stato omesso nel collegamento TIO perché l'esecuzione da sola richiede più di un minuto. L'ho eseguito sul mio laptop e il risultato corretto è stato raggiunto in non più di due ore.

{                             The input
 ~a₀                          is a prefix of
    X√                        X, the square root of which
      ℕ                       is a whole number.
       ∧YcX                   Y concatenated is X.
           ∧Yh?               The input is the first element of Y.
               ∧Yb            The rest of Y,
                  c           concatenated,
                      }       is the output
                   ℕ          which is a whole number.
                    ≜         Make sure that it actually has a value,
                     !        and discard all choice points.
{                     }ⁱ      Keep feeding that predicate its own output until
                        √     its output's square root
                         ℕ    is a whole number
                              which is the output.

Il penultimo è necessario per quando l'input iniziale è già un quadrato perfetto, quindi il primo quadrato perfetto che lo ha come prefisso è esso stesso, ed !è necessario assicurarsi che il backtracking iteri invece di trovare un quadrato concatenato più grande, ma non so davvero perché sia necessario, so solo che 5 produce una risposta sbagliata senza di essa.


(Grazie a un bug nel parser, quell'orribile pasticcio di variabili e s nominate è in realtà più breve dell'uso di un sandwich.)
Unrelated String

0

Perl 6 , 101 byte

my&q={$^k;$_=({++($||=$k.sqrt.Int)**2}.../^$k/)[*-1];+S/$k//}
put (q(get),&q...!(*.sqrt%1))[*-1].sqrt
my &q = {
  $^k; # declare placeholder parameter
  # set default scalar to:
  $_ = ( # a list
    # code block that generates every perfect square
    # larger than the input
    { ++( $ ||= $k.sqrt.Int )**2 }
    ...   # produce a sequence
    /^$k/ # ending when it finds one starting with the argument
  )[*-1]; # last value in sequence

  # take the last value and remove the argument
  # and turn it into a number to remove leading zeros
  +S/$k//
}

put (     # print the result of:
  q(get),     # find the first candidate
  &q          # find the rest of them
  ...         # produce a sequence
  !(*.sqrt%1) # ending with a perfect square
)[*-1]        # last value in sequence
.sqrt         # find the sqrt

0

ES7, 116 byte

n=>{do{for(i=n;!(r=(''+Math.ceil((i*=10)**0.5)**2)).startsWith(+n););n=r.replace(+n,'');r=n**0.5}while(r%1);return r}

Sì, probabilmente potrei salvare un byte usando eval.

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.