Aumenta il numero intero x per alimentare x, senza built-in di esponenziazione


16

Compito: il titolo lo riassume praticamente: aumentare un numero intero x per alimentare x , dove 0<x.

restrizioni:

  • Uso di elevamento a potenza, exp(), ln(), linguistiche e qualsiasi altro potere-correlati built-in, come pow(), x^x, x**xè vietato.
  • Puoi presumere che il dato numero intero corrisponda ai limiti del linguaggio di programmazione che preferisci.

Casi test:

Input | Output
---------------
2     | 4
3     | 27
5     | 3125
6     | 46656
10    | 10000000000

Questo è , quindi vince il programma più breve in byte.


Possiamo accettare l'input come stringa?
Shaggy,

Ho apportato una modifica a questo, sperando che venga riaperta. Ho cancellato la regola 3 e invece ho affermato che dovrebbe essere un programma completo, come probabilmente l'OP intendeva
Mr. Xcoder

Molto meglio, @ Mr.Xcoder ma suggerisco di rimuovere (o riformulare) la seconda restrizione. "Non una funzione" esclude JS dalla partecipazione? Vorrei anche suggerire, ai fini della sfida, che dovremmo avere a manico 0e che specificare i risultati attesi ( 0o 1o uno). Infine, dover gestire numeri interi negativi sarebbe una bella aggiunta alla sfida.
Shaggy,

@Shaggy ha aggiunto js in ... calcolato 0 ^ 0 sul calcolatore Apple e ha restituito 1. Forse 1 dovrebbe essere il valore scelto, perché anche Python ritorna 1per 0^0. Tuttavia, Foundation+ Swift restituisce 0
Mr. Xcoder

1
@ Mr.Xcoder, ho rimosso la "restrizione" che non è necessario gestire 0e invece l' ho specificata 0<xnel lead-in. Ho anche rimosso la restrizione che il codice non dovrebbe generare errori; questo dovrebbe essere ovvio. Sentiti libero di tornare indietro se necessario.
Shaggy,

Risposte:


15

APL (Dyalog) , 4 byte

Per x x , prende x come argomento sinistro e x come argomento destro.

×/⍴⍨

Prova tutti i casi online!

×/ prodotto di

⍴⍨ arg copia arg

E qui eccone uno che gestisce anche numeri negativi:

×/|⍴|*×

Prova tutti i casi!

×/ il prodotto di

| valore assoluto

r epetitions di

| il valore assoluto

* al potere di

× il signum

Il primitivo Power incorporato è:

x*y


9

Mathematica, 16 byte

Ho due soluzioni con questo numero di byte:

1##&@@#~Table~#&

Qui, #~Table~#crea un elenco di ncopie di n. Quindi la Listtesta viene sostituita dalla 1##&quale moltiplica tutti i suoi argomenti insieme.

Nest[n#&,1,n=#]&

Ciò memorizza semplicemente l'input ne quindi si moltiplica 1per n, nvolte.


1
#~Product~{#}&
alephalpha,

1
@alephalpha ah, buon punto. Puoi pubblicarlo come risposta separata.
Martin Ender,

5

JavaScript (ES6), 33 28 25 24 byte

n=>g=(x=n)=>--x?n*g(x):n

Provalo

f=
n=>g=(x=n)=>--x?n*g(x):n
o.innerText=f(i.value=3)()
i.oninput=_=>o.innerText=f(+i.value)()
<input id=i min=1 type=number><pre id=o>


Storia

25 byte

f=(n,x=n)=>--x?n*f(n,x):n

28 byte

n=>eval(1+("*"+n).repeat(n))

33 byte

n=>eval(Array(n).fill(n).join`*`)

4

Bash puro, 43

echo $[$1<2?1:$[$1<2?2:$1]#`printf 1%0$1d`]

Provalo online .

Non sono sicuro se questo sta piegando troppo le regole - non sto usando nessuno dei builtin vietati elencati, ma sto usando la conversione di base.

  • printf 1%0$1dgenera a 1seguito da n 0s
  • $[b#a]è un'espansione aritmetica da trattare acome un bnumero base , che fornisce il risultato richiesto. Sfortunatamente la base <2 non funziona, quindi i ?:bit extra gestiscono l'ingresso n = 1.

L'input massimo è 15, perché bash utilizza numeri interi a 64 bit con segno (fino a 2 31 -1).


Stesso problema che avevo, questo non funziona per x = 1. Tuttavia, approccio molto interessante.
Maxim Mikhaylov,

@MaxLawnboy Grazie per averlo sottolineato - che purtroppo ha gonfiato la mia risposta. Forse posso capire un'altra versione più breve ...
Digital Trauma,

Roba forte.

4

Alice , 13 byte

/o
\i@/.&.t&*

Provalo online!

Spiegazione

/o
\i@/...

Questo è un framework per programmi che leggono e scrivono numeri decimali e funzionano interamente in modalità Cardinale (quindi programmi per la maggior parte dei problemi aritmetici).

.    Duplicate n.
&.   Make n copies of n.
t    Decrement the top copy to n-1.
&*   Multiply the top two values on the stack n-1 times, computing n^n.


3

Gelatina , 3 byte

ẋ⁸P

Provalo online!

Come?

ẋ⁸P - Main link: x             e.g. 4
 ⁸  - link's left argument, x       4
ẋ   - repeat left right times       [4,4,4,4]
  P - product                       256

Accidenti, volevo farlo. : P
HyperNeutrino,

@Jonathan Allan sono 3 byte o 3 caratteri grandi? vediamo il dump esadecimale del codice sorgente, per favore, per prendere la decisione corretta sul bytesize del codice reale. ;-) e apporta le correzioni

1
@ xakepp35 Jelly usa un SBCS e il link byte nell'intestazione punta ad esso. Il programma con hexdump F7 88 50funziona come previsto.
Dennis,

@Dennis grazie per la risposta! non potrei mai immaginare una lingua simile prima =)

3

Cubix , 19 byte

..@OI:1*s;pu!vqW|($

Provalo online!

Passo dopo passo

Si espande su un cubo con lunghezza laterale 2

    . .
    @ O
I : 1 * s ; p u
! v q W | ( $ .
    . .
    . .
  • I:1 Prende l'input, lo duplica e spinge 1. Questo imposta lo stack con un contatore, un moltiplicatore e un risultato.
  • *s; Moltiplica i TOS, scambia il risultato con il precedente e rimuove il precedente.
  • puPorta l'elemento contatore al TOS. Inversione a U. Questo serve per cambiare corsia, ma doveva radere un byte.
  • |($Questo è stato fatto per salvare un byte. Quando colpito, salta il decremento. riflette, decrementa il contatore e salta il no op avvolgendo il cubo.
  • !vqWProva il contatore. Se in verità salta il reindirizzamento, metti il ​​contatore su BOS, cambia corsia sul moltiplicatore. Altrimenti reindirizzare.
  • |sO@questa è la sequenza finale reindirizzata a dal contatore test. Oltrepassa il riflesso orizzontale, scambia il TOS portando il risultato al TOS, uscita e arresto.

3

R, 22 byte

legge xda stdin.

prod(rep(x<-scan(),x))

genera un elenco di xcopie di x, quindi calcola il prodotto degli elementi di tale elenco. Quando x=0, i repritorni numeric(0), che è un vettore numerico di lunghezza 0, ma il proddi quello è 1, quindi 0^0=1con questo metodo, che è coerente con l'esponenza incorporata di R, quindi è abbastanza pulito.

Provalo online!


3

linguaggio macchina x86_64 per Linux, 14 11 10 byte

0:   6a 01                   pushq  $0x1
2:   58                      pop    %rax
3:   89 f9                   mov    %edi,%ecx
5:   f7 ef                   imul   %edi
7:   e2 fc                   loop   5
9:   c3                      retq

Per provarlo online! , compilare ed eseguire il seguente programma C.

const char h[]="\x6a\1\x58\x89\xf9\xf7\xef\xe2\xfc\xc3";

int main(){
  for( int i = 1; i < 4; i++ ) {
    printf( "%d %d\n", i, ((int(*)())h)(i) );
  }
}

2

Rubino, 20 18 byte

-2 byte perché le specifiche sono cambiate e non ho più bisogno di un argomento esponente.

->x{eval [x]*x*?*}

Provalo online!


2

Impilato , 10 byte

{!1[n*]n*}

Provalo online!

Esponenziazione a due argomenti per le stesse dimensioni:

{%1[x*]y*}

Entrambe sono funzioni. Ripete una funzione che si moltiplica 1per i n ntempi.



2

05AB1E , 3 byte

.DP

Provalo online! oppure prova tutti gli esempi

.D  # pop a,b    push b copies of a 
    # 05AB1E implicitly takes from input if there aren't enough values on the stack
    # For input 5, this gives us the array: [5,5,5,5,5]
  P # Take the product of that array
    # Implicit print

Sembra che ti sia piaciuto .D. La prima volta che l'ho visto usato.
Magic Octopus Urn

ah, non capisco cosa stia succedendo qui .. sembra essere troppo esotico e nessuna spiegazione su come funziona. = (

@ xakepp35 Ti aiuta?
Riley,


2

Japt, 4 bytes

ÆUÃ×

Try it online!

Explanation

ÆUÃ×       // implicit: U = input integer
Uo{U} r*1  // ungolfed

Uo{ }      // create array [0, U) and map each value to...
   U       //   the input value
      r*1  // reduce with multiplication, starting at 1          
           // implicit output of result

2

x86 machine code (Linux), 18 bytes

31 c0 ff c0 31 db 39 df 74 07 0f af c7 ff c3 eb f5 c3

It expects a C declaration as follows extern int XpowX(int).

Disassembled

XpowX:
  # edi : input register
  # ebx : counter
  # eax : result register
  xor  %eax, %eax    # result  = 0
  inc  %eax          # result += 1
  xor  %ebx, %ebx    # counter = 0
  loop:
    cmp  %ebx, %edi  # if (counter == input)
    je   done        #   return result
    imul %edi, %eax  # result  *= input
    inc        %ebx  # counter += 1
    jmp   loop
  done:
    ret

1

Brachylog, 6 bytes

g;?j₎×

Try it online!

Explanation

          Example input: 5
g         Group: [5]
 ;?       Pair with the Input: [[5], 5]
   j₎     Juxtapose [5] 5 times: [5, 5, 5, 5, 5]
     ×    Multiply

1

CJam, 7 bytes

ri_a*:*

Try it online!

Explanation

ri       e# Read an int from input
  _      e# Duplicate it
   a*    e# Put the copy in the array and repeat it that many times
     :*  e# Take the product of the array

1

Perl 6, 13 bytes

{[*] $_ xx$_}

$_ xx $_ evaluates to a list of $_ copies of $_ ($_ being the argument to the anonymous function), and then [*] reduces that list with multiplication.


1

CJam, 6 bytes

ri_m*,

Try it online!

ri       e# Read integer
  _      e# Duplicate
   m*    e# Cartesian power. The first argument is interpreted as a range
     ,   e# Number of elements. Implicitly display


1

Röda, 17 bytes

{product([_]*_1)}

Try it online!

It's an anonymous function that takes it's input from the stream.

Explanation:

{product([_]*_1)}
{               } /* An anonymous function */
         [_]      /* An array containing the input value */
            *_1   /* repeated times the input value */
 product(      )  /* Product of all values in the array */

1

dc, 24 23 26 22 bytes

This is my first attempt writing a recursive macro in dc. I am sure it is a sub-optimal solution which can be improved a lot.

dsr1+[lrr1-d1<F*]dsFxp

Try it online!

Edit: Thanks eush77! -4 bytes.


1
Does not work for x=1.
eush77

You can shave off two bytes by replacing lr sequences at the end with two ds at the beginning.
eush77

Actually, you don't need that. Just increment the top of the stack before calling for the first time. This way you will end up with x copies of x on the stack (and 1 of course), and x multiplications thereafter. So the ending can just be plain dsFxp.
eush77

@eush77 I was about to say that removing second lr wouldn't work here. It's my first time golfing in a stack-based language, so it feels very unusual. Thanks for your help!
Maxim Mikhaylov

1

Batch, 58 bytes

@set n=1
@for /l %%i in (1,1,%1)do @set/an*=%1
@echo %n%

Only works for single-digit inputs due to 32-bit arithmetic.


1

brainf*ck, 148 bytes

,[->+>+<<]>>[-<<+>>]++++++++[<------<------>>-]<[->>+>>+<<<<]>>[-<<+>>]>>-[-<<<<<[>[>+>+<<-]>>[<<+>>-]<<<-]>>[-<<+>>]>>>]<<<++++++++[-<<++++++>>]<<.

Try it online!

No built-ins ;)

How it works

,                                       - get ascii input
[->+>+<<]                               - duplicate input
>>[-<<+>>]                              - shift inputs left to start
++++++++[<------<------>>-]             - convert ascii into input numbers
<[->>+>>+<<<<]                          - get loop intervals (same as input #)
>>[-<<+>>]                              - shift input back again
>>-[-<<<<<[>[>+>+<<-]>>[<<+>>-]<<<-]>>  - iterated addition (multiplication)
[-<<+>>]>>>                             - Shift output back into input
]<<<++++++++[-<<++++++>>]<<.            - convert final output to ascii

In a nutshell, this works by multiplying x (the input) by itself x times. (a.k.a. iterating iterated addition). The net result is x^x.

I/O

The program takes a single ASCII input, and processes it as it's ASCII index minus 48. The minus 48 is to normalize inputs of actual numbers (4 becomes 52 -> 52-48 -> 4). To input a number higher than 9, use the next corrosponging ASCII character (: -> 58-48 -> 10). The program ouputs in a similar fashion.

Test I/O

INPUT > PROCESSED INPUT >> OUTPUT > TRANSLATED OUTPUT
1 > 1 >> 1 > 1
2 > 2 >> 4 > 4
3 > 3 >> K > 27

Since there are no printable ASCII characters after an input of 3, it can only print numbers in theory. Though, you can check all inputs do in fact work on visualizers such as this.


1

MATLAB/Octave, 23 bytes

@(n)(prod(n*ones(n,1)))

1

Python, 32 bytes

f=lambda g,z=1:z>g or g*f(g,z+1)

Try it online!


Welcome to PPCG! You don't need to count the f= part, so you can shorten your submission to 30 bytes.
Steadybox

@Steadybox The f= part does need to be counted, because it's recursive, so it relies upon the function being named f in order to work properly
musicman523

@musicman523 Yes, you are right.
Steadybox

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.