Golf x x x kökünü


24

(Ben ... yarım benim şimdiki yaşındayken) Lisenin sıkılmış olsa da, bunu buldum f ( x =) x ( x -1 ) kapsamaktadır, örneğin, bazı ilginç özelliklere sahip olduğunu azami f 0 ≤ için x isimli f ( e ) ve bir izotopun nükleonu başına bağlanma enerjisinin 6 x f ( x ÷ 21) ...

Yine de, dilinizin etki alanındaki herhangi bir sayı için x'in x'in kök dizinini hesaplayan en kısa işlevi veya programı yazın.

Örnek vakalar

Tüm diller için

     -1   >       -1
   ¯0.2   >    -3125
   ¯0.5   >        4
    0.5   >     0.25
      1   >        1
      2   >    1.414
      e   >    1.444 
      3   >    1.442
    100   >    1.047
  10000   >    1.001

Karmaşık sayıları işleyen diller için

   -2   >        -0.7071i
    i   >            4.81         
   2i   >    2.063-0.745i
 1+2i   >   1.820-0.1834i
 2+2i   >   1.575-0.1003i

Sonsuzlukla uğraşan diller için

-1/∞   >   0    (or ∞ or ̃∞)
   0   >   0    (or 1 or ∞)
 1/∞   >   0
   ∞   >   1
  -∞   >   1

Hem sonsuzlukları hem de karmaşık sayıları işleyen diller için

 -∞-2i   >   1      (or ̃∞)

̃∞yönlendirilmiş sonsuzluğu gösterir .


1
İşte olumlu gerçek için bir Wolfram Alpha arsax . xSorgudaki sınırları atlarsanız , Wolfram Alpha x, işlev değerinin karmaşık logaritma (veya benzeri bir karmaşık işlev için) "dal" seçimine bağlı olduğu negatif değerleri içerir .
Jeppe Stig Nielsen

Ondalık ayracı kullanamayan diller ne olacak?
Sızdıran Rahibe

1
@KennyLau Özellikle algoritma işe yararsa, dili desteklediğini söyleyen bir notla göndermekten çekinmeyin.
Adám

Yanıtlar:


38

TI-BASIC, 3 bayt

Ans×√Ans

TI-TEMEL nedenle, belirteçleri kullanarak Ansve ×√her ikisi de tek bir bayt vardır.

açıklama

Ansgirdi vermenin en kolay yoludur; Bu son ifadenin sonucudur. ×√bu, x'in x. kökü için bir fonksiyondur, örneğin 5×√322'dir.


8
Bildiğim kadarıyla anskodlama girişlerini değişkenler olarak saymaktaydı ve kod golf için kabul edilen bir giriş yöntemi gibi görünmüyor . Bu durumda, lütfen tam bir program veya işlev yapın.
kusur,

4
@flawr Ne dediğini anlıyorum ama her zaman böyle yapıldı gibi görünüyor. Belki bir meta gönderisini garanti eder?
NinjaBearMonkey

3
AnsTI-Basic için STDIN / STDOUT'dur.
Timtech

5
stdinve stdoutgenellikle etkileşimli metin girişi ve çıkışı için metin akışlarıdır. Ansetkileşimli değildir, TI-BASIC’teki diğer bazı işlevlerin aksine etkileşimlidir.
Olathe

7
@flawr Sebep Ansgenellikle kabul edilir, değeri herhangi bir ifade tarafından ayarlanır (ifadeler ile ayrılır :). Bu nedenle 1337:prgmXTHROOT, bir şey normal bir dilde CLA'lar vasıtasıyla girişe çok benzeyen 1337'yi girecektir.
lirtosiast

23

Jöle, 2 bayt

Çevrimiçi deneyin!

Nasıl çalışır

*İ    Main link. Input: n

 İ    Inverse; yield 1÷n.
*     Power (fork); compute n ** (1÷n).

Jelly'in yığını yok. Monadik bir zincirdeki monadın takip ettiği bir dyad APL'nin çatalları gibi davranır.
Dennis,

3
Hayır, ^%J'ler bir çatal değildir (Dyalog APL'de bulunmayan) bir kancadır. Jelly soldan sağa olduğundan Jelly ve APL kodunu karşılaştırmak zordur. En yakın eşdeğer , farklı yönden hesaplanan ÷*⊢(ayrıca bir çatal) olacaktır (1/x)**x. Jelly'in atomları aşırı yüklenmediğinden (monadik veya dyadik değildirler, fakat asla ikisi de yoktur), monadic 1,2,1 ve 2,1 forks olabilir.
Dennis,

Açıklama için teşekkürler. Doğal olarak, Jelly (beni ȷ ya da benzeri bir şey olarak adlandırılması gerektiğini düşünüyorum) oldukça merak ediyorum.
Adám

17

Javascript (ES2016), 11 bayt

x=>x**(1/x)

ES6'yı ES6'da nadiren kullanıyorum.


2
x=>x**x**-1ayrıca yine 11 byte için çalışır.
Neil

7
Hepiniz yeni üs işletmecisini selamlayın!
mbomb007

15

Python 3, 17 bayt

lambda x:x**(1/x)

Kendini açıklayan


7
Oldukça hoşuma gidiyor lambda x:x**x**-1, ama daha kısa değil.
32'de seequ

1
@Seeq İfadeniz aynı uzunluktadır, ancak hem Python 2 hem de 3'te çalışma avantajına sahiptir.
mathmandan

1
Python 2 en kısa lambda x:x**x**-1, yani 2 ve 3 aynıdır
mbomb007

Bu cevabı uzun zamandır bulamadım ve bulduğumda gerçekten sinirlenmiştim.

12

Haskell, 12 11 bayt

Biraz sihir yaptığınız için teşekkürler @LambdaFairy:

(**)<*>(1/) 

Eski sürümüm:

\x->x**(1/x)

4
(**)<*>(1/)11 bayttır.
Lambda Perisi

@LambdaFairy Teşekkürler! Açıklamanın bir sakıncası var mı? Kısmen uygulanmış fonksiyonlarla biraz sihir yapıyorsunuz gibi gözüküyor ama Haskell için oldukça yeni olduğum için bunun nasıl çalıştığını gerçekten anlamıyorum =)
kusurlu,

Bu, 1 argüman işlevinin uygulamalı bir işlevci olarak kabul edilebileceği gerçeğini kullanır ("okuyucu monad"). <*>Operatör bir işlevi ve bir değer üreten bir Uygulamalı üreten bir uygulamalı alır ve değere fonksiyonu uygular. Bu nedenle, bu durumda, 2-argüman işlevini 1-argüman işlevine uygulamak için zihin bükme yöntemi.
Matematiksel

2
Fonksiyon <*>3 argümanları, iki işlev alır fve gbir argüman x. Şöyle tanımlanmıştır (<*>) f g x = f x (g x), bu geçerlidir yani fetmek xve g x. Burada kısmen uygulanmış fve gdışarıda bırakılmış x, nerede f = (**)ve g = (1/)(bir başka kısmen uygulanmış fonksiyonun (bir bölüm) argümanının karşılıklı değerini hesaplayan). Yani ( (**)<*>(1/) ) xedilir (**) x ((1/) x): Infix yazılmış veya x ** ((1/) x)ve çözülmesi bölümle: x ** (1/x). - Not: <*>Burada işlev bağlamında kullanılır ve diğer bağlamlarda farklı davranır.
nimi

@ nimi Yani, Sbirleştiricinin eşdeğeri, yani S (**) (1 /)?
Neil

10

J, 2 bayt

^%

Çevrimiçi deneyin! .

Nasıl çalışır

^%  Monadic verb. Argument: y

 %  Inverse; yield 1÷y.
^   Power (hook); compute y ** (1÷y).

Bu cevabı ben yazacaktım. Bu konuda çok yavaşım.
Bijan

1
@Bijan Bir yıldan fazla bir süredir yavaş görünüyor. : P
Dennis,

Anladım, şimdi sadece bir haftadır golf oynuyorum.
Bijan

9

Pyth, 3 bayt

@QQ

Önemsiz zorluk, önemsiz çözüm ...

(rekabetçi olmayan, 1 bayt)

@

Bu, bu mücadeleyi yayınlayan Pyth sürümünde bulunan örtük giriş özelliğini kullanır.


Bu çözüm, örtük girdi özelliğini öne sürüyor mu?
Leaky Nun

@KennyLau Evet, uzun zamandır. Ama yine de bir baytlık çözümü değiştirdim.
Doorknob


8

Java 8, 18 bytes

n->Math.pow(n,1/n)

Java isn't in last place?!?!

Test with the following:

import java.lang.Math;

public class Main {
  public static void main (String[] args) {
    Test test = n->Math.pow(n,1/n);
    System.out.println(test.xthRoot(6.0));
  }
}

interface Test {
  double xthRoot(double x);
}

It's the fact that it's a function
CalculatorFeline

6

Java, 41 bytes

float f(float n){return Math.pow(n,1/n);}

Not exactly competitive because Java, but why not?


1
Welcome to PPCG! I think you might be missing a return type on this function.
a spaghetto

Oops, got sloppy. A Java 8 answer already beat this one of course...
Darrel Hoffman

6

MATL, 5 bytes

t-1^^

Try it online!

t       % implicit input x, duplicate
 -1     % push -1
   ^    % power (raise x to -1): gives 1/x
    ^   % power (raise x to 1/x). Implicit display

6

Mathematica, 8 7 4 7 bytes

#^#^-1&

More builtin-only answers, and now even shorter! Nope. By definition, the next answer should be 13 bytes. (Fibonacci!) The pattern is still broken. :(


1
#^#^-1& saves 1 byte.
njpipeorgan

NOW it is golfed.
Adám

1
NOW it is golfed.
CalculatorFeline

1
When Mthmtca is released, we are going to rule this board.
Michael Stern

1
Surely just Surd isn't valid as it requires two arguments?
LLlAMnYP

5

Perl 5, 10 bytes

9 bytes plus 1 for -p

$_**=1/$_

5

R, 19 17 bytes

function(x)x^x^-1

-2 bytes thanks to @Flounderer


Why not x^(1/x) ? Edit: x^x^-1 seems to work too.
Flounderer

That's a snippet, and apparently people don't like snippets.
CalculatorFeline

@CatsAreFluffy it is the definition of a function.
mnel

5

Ruby, 15 Bytes

a=->n{n**n**-1}

Ungolfed:

-> is the stabby lambda operator where a=->n is equivalent to a = lambda {|n|}


5

NARS APL, 2 bytes

√⍨

NARS supports the function, which gives the ⍺-th root of ⍵. Applying commute (⍨) gives a function that, when used monadically, applies its argument to both sides of the given function. Therefore √⍨ xx √ x.

Other APLs, 3 bytes

⊢*÷

This is a function train, i.e. (F G H) x(F x) G H x. Monadic is identity, dyadic * is power, and monadic ÷ is inverse. Therefore, ⊢*÷ is x raised to 1/x.


5

Python 2 - 56 bytes

The first actual answer, if I'm correct. Uses Newton's method.

n=x=input();exec"x-=(x**n-n)/(1.*n*x**-~n);"*999;print x

Functions are okay.
CalculatorFeline

5

CJam, 6 bytes

rd_W##

Try it online!

How it works

rd     e# Read a double D from STDIN and push it on the stack.
  _    e# Push a copy of D.
   W   e# Push -1.
    #  e# Compute D ** -1.
     # e# Compute D ** (D ** -1).


4

Pylons, 5 bytes.

ideAe

How it works.

i # Get command line input.
d # Duplicate the top of the stack.
e # Raise the top of the stack to the power of the  second to the top element of the stack.
A # Push -1 to the stack (pre initialized variable).
e # Raise the top of the stack to the power of the second to the top element of the stack.
  # Implicitly print the stack.


4

C++, 48 bytes

#include<math.h>
[](auto x){return pow(x,1./x);}

The second line defines an anonymous lambda function. It can be used by assigning it to a function pointer and calling it, or just calling it directly.

Try it online


Does ^ not work in C++ as it does in C?
takra

2
@minerguy31: ^ is bitwise xor in C (and C++).
marinus

4

Milky Way 1.6.5, 5 bytes

'1'/h

Explanation

'      ` Push input
 1     ` Push the integer literal
  '    ` Push input
   /   ` Divide the STOS by the TOS
    h  ` Push the STOS to the power of the TOS

x**(1/x)


Usage

$ ./mw <path-to-code> -i <input-integer>

4

O, 6 bytes

j.1\/^

No online link because the online IDE doesn't work (specifically, exponentiation is broken)

Explanation:

j.1\/^
j.      push two copies of input
  1\/   push 1/input (always float division)
     ^  push pow(input, 1/input)

oh hey you did it yay
phase


4

Pyke (commit 29), 6 bytes

D1_R^^

Explanation:

D      - duplicate top
 1_    - load -1
   R   - rotate
    ^  - ^**^
     ^ - ^**^

Can haz link pls?
cat

Oh, I thought you meant there's no implementation available. Yes, the interpreter doesn't have to be hosted, just a link to the repo / source (or docs) will suffice
cat

4

C# - 18 43 41 bytes

float a(float x){return Math.Pow(x,1/x);}

-2 byes thanks to @VoteToClose

Try it out

Note:

First actual attempt at golfing - I know I could do this better.


Welcome to the crowd! It is exactly because of newcomers that I make trivial challenges like this.
Adám

Fixed. Thanks for informing me about this
EnragedTanker

@crayzeedude No problem at all. Nice job and again, welcome to PPCG!
Alex A.

Does C# have float?
Addison Crump

Indeed it does.
EnragedTanker

4

C, 23 bytes

#define p(a)pow(a,1./a)

This defines a macro function p which evaluates to the ath root of a.

Thanks to Dennis for reminding me that gcc doesn't require math.h to be included.

Thanks to @EʀɪᴋᴛʜᴇGᴏʟғᴇʀ for reminding me that the space after the first ) is not needed.

Try it online


With GCC, you don't need to include math.h.
Dennis

-1 byte: #define p(a)pow(a,1./a)
Erik the Outgolfer

4

dc, 125 bytes

15k?ddsk1-A 5^*sw1sn0[A 5^ln+_1^+ln1+dsnlw!<y]syr1<y1lk/*sz[si1[li*li1-dsi0<p]spli0<p]so0dsw[lzlw^lwlox/+lw1+dswA 2^!<b]dsbxp

Unlike the other dc answer, this works for all real x greater than or equal to 1 (1 ≤ x). Accurate to 4-5 places after the decimal.

I would have included a TIO link here, but for some reason this throws a segmentation fault with the version there (dc 1.3) whereas it does not with my local version (dc 1.3.95).

Explanation

As dc does not support raising numbers to non-integer exponents to calculate x^(1/x), this takes advantage of the fact that:

Advantage

So, to calculate ln(x), this also takes advantage of the fact that:

Advantage2

whose definite integral from 1 to (b = x) is numerically-approximated in increments of 10^-5 using the following summation formula:

Summation Formula.

The resulting sum is then multiplied by 1/x to get ln(x)/x. e^(ln(x)/x) is then finally calculated using the e^x Maclaurin Series to 100 terms as follows:

e^x Maclaurin Series.

This results in our relatively accurate output of x^(1/x).


1
+1 This has got to be one of the best dc answers out there. I'm bookmarking this!
Kritixi Lithos

@KritixiLithos Thank you! I appreciate the kind words. :)
R. Kap

3

PHP 5.6, 32 30 29 bytes

function($x){echo$x**(1/$x);}

or

function($x){echo$x**$x**-1;}

30->29, thank you Dennis!

Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.