You must make a that outputs the square of the input in one language and the square root of the input in another. The shortest answer in bytes wins!

You must have a precision of at least 3 decimal places, and the input will always be a positive float.


40 Answers 40


C and C++, 68 65 bytes

float f(float n){auto p=.5;return pow(n,2-p*3);}

Original answer:

float f(float n){return pow(n,sizeof('-')-1?2:.5);}

For both versions, C produces n^2 and C++ produces sqrt(n).

  • 29
    \$\begingroup\$ +1 as a "Ha!" for all those people who treat C and C++ as the same thing. \$\endgroup\$
    – DocMax
    Commented Apr 11, 2017 at 22:19
  • 24
    \$\begingroup\$ @CAD97: In C, auto means "allocate on the stack". The keyword is fairly useless because that's the default anyway, so C++ repurposed it to mean something else. In C, though, it doesn't express any opinion about the type of p (it's a storage class, not a type), so it counts as an int by default (this default-to-int behaviour is discouraged nowadays, and likely only exists because some of C's predecessors didn't have data types at all, but compilers still understand it). And of course, (int)0.5 is 0. \$\endgroup\$
    – user62131
    Commented Apr 12, 2017 at 1:46
  • 2
    \$\begingroup\$ This is brilliant. \$\endgroup\$
    – Quentin
    Commented Apr 12, 2017 at 8:23
  • 1
    \$\begingroup\$ Found a Stack Overflow question about it. \$\endgroup\$
    – YSC
    Commented Apr 12, 2017 at 10:47
  • 10
    \$\begingroup\$ I think the explanation for this answer would be improved by editing in @ais523's comment explaining why C produces n^2. \$\endgroup\$
    – Brian J
    Commented Apr 12, 2017 at 14:59

Python 2 & Python 3, 23 21 bytes

lambda n:n**(1/2or 2)

Python 2.x produces n^2, Python 3.x produces sqrt(n).

2 bytes saved thanks to @Dennis!

  • \$\begingroup\$ this is so cool! \$\endgroup\$
    – njzk2
    Commented Apr 12, 2017 at 18:13
  • \$\begingroup\$ Why? Is it the lack of space before or? \$\endgroup\$
    – chx
    Commented Apr 14, 2017 at 1:11
  • \$\begingroup\$ @chx In Py2, / does integer division (1/2==0). In Py3, it does floating point division (1/2==0.5). 0 is falsey. \$\endgroup\$
    – anon
    Commented Apr 14, 2017 at 3:04
  • \$\begingroup\$ then why not remove the space after or? \$\endgroup\$
    – chx
    Commented Apr 14, 2017 at 3:09
  • 1
    \$\begingroup\$ @chx removing the space after or will cause python to read or2 as a function or variable name. You can remove the space before or though, as python variables/functions can't start with a number, so 2or is parsed as 2 or. \$\endgroup\$
    – Riker
    Commented Apr 27, 2017 at 14:44

Jolf and MATL, 1 byte


Square root in Jolf, square in MATL.

Try it online! (MATL)

Try the Jolf code. Only works on Firefox.

These are both 1 byte, as MATL and Jolf both use ASCII/extended ASCII codepages, so all commands are 1 byte.


2sable / Jelly, 2 bytes


2sable computes the square. Try it online!

Jelly computes the square root. Try it online!

How it works


*   Read the input twice and compute the product of both copies.
    This pushes the square of the input.
 .  Unrecognized token (ignored).


 .  Numeric literal; yield 0.5.
*   Raise the input to the power 0.5.
    This yields the square root.
  • 8
    \$\begingroup\$ It's like these languages were created just for this challenge \$\endgroup\$ Commented Apr 12, 2017 at 10:10

C (clang) and Python, 109 107 69 53 bytes

lambda n:n**.5;'''*/
float a(i){return i*i;}//'''

C: Try it online!

Python: Try it online!

Works by using comments to polyglot. The rest is pretty explanatory.

First time using C!

  • Saved quite a few bytes thanks to @Riker.
  • Saved 2 bytes by removing unnecessary whitespace.
  • Saved very many bytes by using a function for C instead of STDIN/OUT.
  • Saved 16 bytes thanks to @Delioth by removing import statement at the top.
  • \$\begingroup\$ I believe you can remove one newline after the C comment (line 2, last character) since C doesn't need whitespace and it's already a literal string for python. Since you aren't returning any special code, you can omit the return 0; from the end- C99 holds an implicit return of 0 on main() specifically. Source \$\endgroup\$
    – Delioth
    Commented Apr 13, 2017 at 20:08
  • \$\begingroup\$ @Delioth It actually made more sense just to use the function, and wipe out the io. \$\endgroup\$
    – sporkl
    Commented Apr 13, 2017 at 20:26
  • \$\begingroup\$ Oh, yeah- much better. Do you even need to include stdio.h in that case? \$\endgroup\$
    – Delioth
    Commented Apr 13, 2017 at 20:29
  • \$\begingroup\$ @Delioth I don't. Whoops! \$\endgroup\$
    – sporkl
    Commented Apr 13, 2017 at 20:31

Ohm and Jelly, 3 bytes

Outputs the square in Ohm, the square root in Jelly.

Ohm and Jelly use different single-byte codepages, so the program will appear differently in each encoding.

xxd hexdump of the program:

00000000: fd7f 0a                                  ...


Using Jelly's codepage, it appears like this:


Jelly takes the bottom most line to be its main link, and ignores the other links unless specifically called. So here it just does the square root (½) and implicitly outputs it.


Using Ohm's codepage (CP437), it appears like this:


² is the square function, and and are both undefined, so the program just squares the implicitly read input and implicitly outputs it.

  • \$\begingroup\$ Nice! The byte count is fine. \$\endgroup\$
    – user58826
    Commented Apr 11, 2017 at 18:32
  • \$\begingroup\$ I edited my answer to 5 bytes because of this as well, good catch. \$\endgroup\$ Commented Apr 11, 2017 at 18:33
  • \$\begingroup\$ Wow, the first Ohm answer not written by me! Well done! \$\endgroup\$ Commented Apr 11, 2017 at 18:33
  • \$\begingroup\$ If you use the Jelly code page to get the ½ at a byte, what does the ² map to? Is it just junk that is still ignored? And vice-versa for Ohm? Then it would seem to be 2 bytes. \$\endgroup\$ Commented Apr 11, 2017 at 18:34
  • 1
    \$\begingroup\$ I'll make up an example, since I don't want to bother looking up the actual code points. Suppose that ² in Ohm is at code point 5. Code point 5 in Jelly is % and does nothing, so it doesn't matter what the first line is. Suppose that ½ in Jelly is at 27, and code point 27 in Ohm is J and does nothing, so it doesn't matter what the second line is. Thus, if you have a file of 00000101<newline>00011011, it's 3 bytes. I guess the only problem is if the newline is at a different location in the code pages. \$\endgroup\$ Commented Apr 11, 2017 at 18:40

C89 and C99, 47+3 = 50 bytes

float f(float n){return n//*

Requires -lm flag (+3)

C89 produces n^2, C99 produces sqrt(n). To test in C89, Try it online!

Getting C89 to do the sqrt version ought to take less code, but it insists on implicitly declaring the sqrt function with ints, so this is the best I could manage.


Octave / MATLAB, 31 29 bytes


This outputs the square in Octave, and the square root in MATLAB.


The syntax is of course identical in MATLAB and Octave (for this little piece of code at least).

This creates an anonymous function:

@(x)                                 % Take x as input
    x^(                     )        % Raise x to the power of ...   
               version                 % Returns the version number
                                       % 4.2.0 in Octave, 
                                       % ' (R2017a)' in MATLAB
               version>60              % 'R' is larger than 60. All others are smaller
         3*any(version>60)/2           % Checks if there is an 'R' and multiplies it by 1.5 if it is.
       2-3*any(version>60)           % 2-1.5*(is there an 'R')

Basic / Delphi – 6 characters


Square root in Basic and square in Delphi.

You can use a debugger to inspect the expression, thereby fulfilling any output requirements!

  • 2
    \$\begingroup\$ Does this take input by itself? \$\endgroup\$
    – Riker
    Commented Apr 12, 2017 at 17:31
  • \$\begingroup\$ No, but neither do some other submissions, including the C/C++ one. \$\endgroup\$
    – user15259
    Commented Apr 13, 2017 at 2:53
  • \$\begingroup\$ Still invalid though, that doesn't change anything. I'll try to comment on those also. \$\endgroup\$
    – Riker
    Commented Apr 13, 2017 at 3:05
  • 1
    \$\begingroup\$ Can you link any that don't? I can't find any. The C/C++ one is a function, doesn't take input, instead a parameter. \$\endgroup\$
    – Riker
    Commented Apr 13, 2017 at 3:21
  • 4
    \$\begingroup\$ Yes, but what is x? You can't assume it's saved to a value. But you might actually be able to remove the (x), and label it as returning a function. \$\endgroup\$
    – Riker
    Commented Apr 13, 2017 at 12:59

05AB1E / Fireball, 3 bytes

The following bytes make up the program:

FD B9 74

05AB1E calculates square root, Fireball squares.

Explanation (05AB1E - ý¹t):

ý       Pushes an empty string to the stack (not entirely sure why)
 ¹      Push first input
  t     Square root

Explanation (Fireball - ²╣t):

²       Square input
 ╣      Unassigned
  t     Unassigned

Sometimes, it helps to have an incomplete language ;)

  • 1
    \$\begingroup\$ 05AB1E and Fireball use different encodings. Does this affect the programs? \$\endgroup\$
    – Dennis
    Commented Apr 11, 2017 at 18:32
  • \$\begingroup\$ @Dennis I didn't think about that. So saving the same program in different encodings doesn't count for polygots? \$\endgroup\$
    – Okx
    Commented Apr 11, 2017 at 18:34
  • 5
    \$\begingroup\$ Afaik, the default is that the byte streams must match. \$\endgroup\$
    – Dennis
    Commented Apr 11, 2017 at 18:37

PHP7 + JavaScript, 62 61 58 bytes

This was actually more challenging than I expected! I am quite surprised of how long my code is.


How does it work?

This works by selecting the code to run, from the array.
PHP and JavaScript detection is made with +![].

In PHP, [] (empty array) is a falsy value, while in JavaScript it is a truthy value (objects (except null) are always truthy, even new Boolean(false) is truthy!).
But, I need to get it to a numeric value, so, I just use a not (!) and convert it to integer (with the +).
Now, PHP yields the value 1, while JavaScript yields 0.
Placing the code inside an array, at those indexes, will allow us to select the right code for the desired language.
This can be used as [JS,PHP][+![]], to get the code of the right language.

On previous polyglots, I've used '\0'=="\0", which is true in JavaScript (since \0 is parsed as the NULL-byte) and false in PHP (the '\0' won't be parsed as the NULL-byte, comparing the literal string \0 with the NULL-byte).
I'm happy that I've managed to reduce this check to +!'0'.
I'm even more happy about @rckd, which reduced it to the current version!

From there on, it simply evals the code required.


PHP will execute echo$argv[1]**.5 (equivalent to echo sqrt($argv[1]);, square-root the number), receiving the value from the 2nd argument and displays it in the standard output.


JavaScript executes alert((_=prompt())*_), which displays the squared number in an alert.

Thank you to @rckd for saving 1 byte, and @user59178 for saving 3 bytes!

  • 1
    \$\begingroup\$ ![] will save you 1 byte :-) \$\endgroup\$
    – rcd
    Commented Apr 12, 2017 at 15:25
  • 1
    \$\begingroup\$ @rckd Holy cow! Totally forgot about empty arrays. Thank you! I've edited into the question, with an explanation on how it works. \$\endgroup\$ Commented Apr 12, 2017 at 16:05
  • 1
    \$\begingroup\$ you can save 3 bytes by using echo$argv[1]**.5 rather than echo sqrt($argv[1]) \$\endgroup\$
    – user59178
    Commented Apr 13, 2017 at 11:34
  • \$\begingroup\$ Wow, nice saving! Thank you! I've added it into the answer. \$\endgroup\$ Commented Apr 13, 2017 at 12:35

05AB1E and Jelly, 4 bytes


(05AB1E) - (Jelly)

nq   # Ignored by Jelly, push n**2 in 05AB1E then quit.
  Ɠ½ # Ignored by 05AB1E due to quit, push sqroot of input in Jelly.

Someone else made a good point, I guess since the UTF-8 characters do not share the same operation across code pages that they are technically 2-bytes each to encode. However, when looking at this in terms of the hex dump:

6e 71 93 0a

In 05AB1E's CP1252 encoding this results in:


Meaning it will still output the square and quit, ignoring the rest. When these bytes are encoded using Jelly's codepage:


Which is the original intended code, when executed, results in the desired result of taking the input and taking the sqrt.

  • 2
    \$\begingroup\$ This is actually 6 bytes in UTF-8, as both Ɠ and ½ require two bytes to be encoded. However, the byte sequence 6e 71 93 0a (nqƓ½ for Jelly, nq“\n for CP-1252) should work in both languages. \$\endgroup\$
    – Dennis
    Commented Apr 11, 2017 at 18:37
  • \$\begingroup\$ @Dennis ½ being on both code-pages doesn't allow for it to count as a single because they're different operations I assume? I'm still fuzzy on the whole code-page thing. \$\endgroup\$ Commented Apr 11, 2017 at 18:47
  • 1
    \$\begingroup\$ Scoring in bytes means were counting byte streams. Unless the interpreter actually supports encoding some characters in one code page and other characters in another, we cannot do this for scoring purposes. \$\endgroup\$
    – Dennis
    Commented Apr 11, 2017 at 18:52
  • 4
    \$\begingroup\$ @carusocomputing your submission is the 4 bytes 6e 71 93 0a so there's no "theoretically" about claiming 4 bytes. Just claim 4 bytes. It just so happens that in 05AB1E's standard encoding, it reads one thing which does what you want, while in Jelly's standard encoding, it reads another which does what you want. As an aside, just because 2 encodings can encode the same character doesn't mean that character will be the same in both of them. Just think of encodings like a numeric cypher with a lookup table already shared and hopefully that'll give you a good starting mental-model. \$\endgroup\$
    – Dave
    Commented Apr 12, 2017 at 7:20
  • \$\begingroup\$ @Dave I must've misinterpreted Dennis then. \$\endgroup\$ Commented Apr 12, 2017 at 13:42

Python 2 and Forth, 43 33 bytes

( """ )
\ """);lambda n:n*n

Try it online: Python 2 (square) | Forth (sqrt)

This evaluates to an anonymous function in Python, and a built-in function fsqrt in Forth. Python can have a named function f for 2 bytes more by putting f= in front of the lambda.

The Forth program takes a floating point literal, which in Forth must be written in scientific notation. Pi truncated to 3 decimal places (3.141) would be written like this:


JavaScript (ES6) / JavaScript (ES7), 52 bytes


Returns the square of the input in ES7 and the square root in ES6. Quite difficult to test, unless you have an older browser which support ES6 but not ES7.



  • \$\begingroup\$ Clever! Nice job on this one! \$\endgroup\$
    – user58826
    Commented Apr 12, 2017 at 13:12
  • \$\begingroup\$ Is there a reason for the backticks? Seems like single quotes would do the job. \$\endgroup\$
    – JLRishe
    Commented Apr 12, 2017 at 15:54
  • \$\begingroup\$ @JLRishe Nope, no reason :) \$\endgroup\$
    – Tom
    Commented Apr 12, 2017 at 16:31
  • 3
    \$\begingroup\$ a**.5 and a*a saves some bytes reversing type \$\endgroup\$
    – l4m2
    Commented Apr 21, 2021 at 19:27

CJam / MATL, 8 bytes


Computes the square in CJam (Try it online!) and the square root in MATL (Try it online!).

Explanation of square in CJam

ld    e# Read input line and interpret as a double
_     e# Duplicate
*     e# Multiply. Pops the input number twice, pushes its square
G     e# Push 16
X     e# Push 1
^     e# Bitwise XOR. Pops 16 and 1, and pushes 17
!     e# Negate. Pops 17, pushes 0
      e# Implicitly display. This prints the squared input with decimals,
      e# immediately followed by the 0 coming from the negate operation
      e# Even if the square of the input number is an integer, say 5,
      e# it is displayed as 5.0, so including an extra 0 always gives a
      e# correct result

Explanation of square root in MATL

l      % Push 1. This is a number or equivalently a 1×1 array
d      % Consecutive differences. Pops 1, pushes [] (empty array)
_      % Negate (element-wise). This leaves [] as is
*      % Implicitly input a number and push it. Multiply (element-wise): 
       % pops [] and the input number, pushes []
G      % Push input number again
X^     % Square root. Pops number, pushes its square root
!      % Transpose. For a number (1×1 array) this does nothing
       % Implicitly display. The stack contains [] and the result; but 
       % [] is not displayed at all
  • \$\begingroup\$ Hey! Nice submission! Care to add an explanation like other answers? \$\endgroup\$
    – user58826
    Commented Apr 12, 2017 at 0:56
  • \$\begingroup\$ @programmer5000 I fixed an error and added the explanations \$\endgroup\$
    – Luis Mendo
    Commented Apr 12, 2017 at 1:23

C, Operation Flashpoint scripting language, 52 bytes

;float f(float x){return sqrt(x);}char*

In an OFP script, a semicolon at the beginning of a line makes that line a comment, whereas C doesn't care about the additional semicolon.


Try it online!

OFP scripting language:

Save as init.sqs in the mission folder, then call it with hint format["%1", 2 call F].

Result: enter image description here

  • \$\begingroup\$ Okay, this is pretty cool. How'd you think of using that scritping lang? \$\endgroup\$
    – Riker
    Commented Apr 17, 2017 at 20:00
  • \$\begingroup\$ @Riker Operation Flashpoint always was one of my favorite games; I used to do lots of stuff in it with its scripting language. \$\endgroup\$
    – Steadybox
    Commented Apr 17, 2017 at 20:48

Vyxal, Grok 10 12 bytes

Edit: In my first version, I forgot that casting to int would remove precision in the Vyxal code. Added +2 bytes to fix it.


Vyxal (Square Root):

              # Implicit input
I             # Cast to int
 √            # Square root
  `#:Yp*zq`   # Push string
           _  # Delete string
              # Implicit output

Try it Online in Vyxal!

Grok (Square):

I√            # Push '√' to the register
  `#          # Skip ‘#’ command
    :         # Take input from STDIN
     Yp       # Duplicate
       *z     # Multiply and output as int
         q    # Quit
          `_  # Never gets executed

Try it Online in Grok!


PHP and CJam, 30 29 25 bytes


Calculates the square in PHP and the square root in CJam. Has to be run using -r in PHP.


Raises the first command line argument ($argv[1]) to the power 2 and outputs it. Here $argv[1] is actually put as an inline variable in a string, which is cast to a number before doing the exponentiation. This is because v is not a valid instruction in CJam and will cause it to error out while parsing, but putting it in a string won't cause any problems.

# starts a comment, so everything after is ignored.

Try it online!


The first part of the code, ECHO"$argv[1]"**2;# pushes a bunch of values and does a bunch of operations, all of which are thoroughly useless. The only important thing is that they doesn't cause any errors, because right afterwards is ];, which wraps the entire stack in an array and then discards it.

After that, it reads a double from input (rd), and gets its square root (mq), and implicitly outputs it.

Try it online!


Desmos and Pip, 12 bytes


Run in Desmos

Run in Pip


The first line is four undefined variables multiplied together. Desmos complains about it, but ultimately it's a no-op.

The second line defines a function f(y) as y times y (with an implicit multiplication operator). This function can be used in other lines and will return the square of any argument number. As a bonus, we also get to see a graph of x = f(y).


RTa calculates the square root of the command-line argument a, and Y stores the result in y. The second line parses as three expressions:

  • f (evaluates to the main function)
  • (y)=y (evaluates to 1 because y always equals itself)
  • y (evaluates to the value stored in y previously)

The last of these expressions ends the program and is therefore autoprinted.


Python / PARI/GP, 60 bytes


Basically a modification from the C / Python answer.
Python does square. PARI/GP does square root.
Takes input from stdin.

Python: Try It Online!

PARI/GP: Try It Online!


Reticular / Befunge-98, 15 bytes

2D languages!




/          divide top two (no-op)
 &         read decimal input
  :        duplicate
   *       square
    .      output
     @     terminate


/           mirror up, then right

 i          read line of input
  n         cast to number
   :o#      square root
      p     print
       ;    terminate

QBIC / QBasic, 26 18 bytes

input a

In QBasic, it takes a number, and prints that number squared. The rest of the code is ignored because QBasic sees it as a comment (').

QBIC uses the same input statement. It then goes on to print that same number squared, then raised to the power of a quarter, effectively rooting it twice. This is because 'is seen as a code literal: Pure QBasic code that is not parsed by QBIC.


GolfScript/Befunge, 15 bytes



#>      // jumps over the arrow
  &     // takes an integer as input
   :*   // multiplies the top of the stack by itself
     .  // outputs as integer
      @ // halts
~2-1??  // is not executed


#>&:*.@ // is a comment
~       // evaluates the input string
 2-1?   /* calculates 2^-1 = 1/2 (GolfScript does not support non-integers, but
           due to a missed int cast in the interpreter, they can be generated with
           the exponent function */
     ?  // calculates x^1/2 = sqrt(x)
        // the stack is output implicitly

This is my first golf, please let me know if I'm doing something wrong :)

  • Edited to be more portable, thanks to Wzl
  • \$\begingroup\$ Welcome to Code Golf! This looks really neat. \$\endgroup\$ Commented Apr 20, 2021 at 18:14
  • \$\begingroup\$ I believe in some befunge versions (98?) space is not an instruction, so it will skip over the &. Your program is working, but you could change it to another character for portability :) \$\endgroup\$
    – Wezl
    Commented Apr 20, 2021 at 18:18

Vyxal and ><> (Fish), 10* bytes


Try it in Vyxal (Square root)

*this is 8 bytes in Vyxal but 10 in ><>. I'm scoring them both in UTF-8.

Try it in ><> (Square)


What Vyxal sees:

<       # less than
 ?      # push input
  √     # sqrt
   ,    # print that sqrt
        # (rest doesn't matter)

What ><> sees:

<     # point left and wrap around executing the following
 :    # dup
  *   # multiply
   n  # output
    ; # end execution

Thunno 2 and Vyxal, 4 bytes

Thunno 2 encoding:


Vyxal encoding:


This looks like two different programs, since Thunno 2 and Vyxal have different encodings, but it's really the same sequence of bytes.


(Thunno 2: square root)

Try it Online! (Vyxal: square)


Ẋ,$ƭ  # Implicit input
Ẋ,    # (No effect)
  $   # Push the input
   ƭ  # Square root
      # Implicit output

²,$₃  # Implicit input
²     # Square the input
 ,    # Print the result
  $₃  # (No effect)

><> / Jelly, 9 bytes (7 bytes code + 2 for the '-v' flag in ><>)

Man, I'm really having fun with the Jelly link structure.


Calculates the square in ><> , and the square root in Jelly.

  • \$\begingroup\$ Are you allowed to not use the -v in jelly too? \$\endgroup\$
    – Riker
    Commented Apr 12, 2017 at 17:30
  • \$\begingroup\$ The use of -v is, in my opinion, in line with the [top-voted answer[(codegolf.meta.stackexchange.com/a/11431/44874) on a meta querstion handling this case. The ><> interpreter needs that -v and this is therefor the simplest possible invocation. \$\endgroup\$
    – steenbergh
    Commented Apr 13, 2017 at 9:43

Python 3 + JavaScript, 101 bytes

0//1or exec("function=lambda a:(lambda b:a);x=0")
f=(function(x)(x**y))//1 or(lambda x:x**y)

Square root in JS, square in Python.

Works on Firefox (tested on FF 52) and requires (function(x) x)(42) === 42 being valid syntax. Also requires ES7 for the ** operator.

  • \$\begingroup\$ Tested on Firefox and it is working. Is it possible to use x=>x**y instead? Or Python will choke on that? \$\endgroup\$ Commented Apr 12, 2017 at 16:06
  • \$\begingroup\$ @IsmaelMiguel python doesn't support arrow functinos. \$\endgroup\$
    – Riker
    Commented Apr 13, 2017 at 3:16
  • \$\begingroup\$ This doesn't work for python. Function isn't a keyword. \$\endgroup\$
    – Riker
    Commented Apr 13, 2017 at 3:16
  • \$\begingroup\$ It does work. Since function is not a keyword, it's a valid identifier. So I just assigned a noop function to it (inside the execstatement). \$\endgroup\$
    – kjaquier
    Commented Apr 18, 2017 at 10:11

macOS Bash and sh, 24 bytes

p=^4 :

On the Mac, sh is bash running in Posix mode, and in this case as per https://www.gnu.org/software/bash/manual/html_node/Bash-POSIX-Mode.html:

Assignment statements preceding POSIX special builtins persist in the shell environment after the builtin completes

Thus for sh, the variable p has the value ^4 after the : is run, but for bash, the variable p only has this value while : is run, and is empty afterwards.

Being still really bash under the covers, some bashisms such as <<< herestrings still work for both the bash and sh cases.

Bash and dash (and GNU utils), 27

On Ubuntu 16.01, sh is a symlink to dash, which doesn't do <<< herestrings. So we have this instead:

p=^4 :
echo "sqrt($1)$p"|bc

Try it online.

  • \$\begingroup\$ Nice use of a different mode/ env! \$\endgroup\$
    – user58826
    Commented Apr 12, 2017 at 23:29
  • \$\begingroup\$ This is much better than my version! \$\endgroup\$
    – Dave
    Commented Apr 13, 2017 at 6:55

bash and sh, 48 bytes

Update: I must concede defeat. Digital Trauma's bash/sh answer is far more elegant than this one.

bc -l<<<"sqrt($1^(($(kill -l|wc -l)*3-3)/7+1))"

bash produces n^2, sh produces sqrt(n).

bc is only needed so that sqrt can be calculated. The difference in behaviour is between bash and sh.

OK, technically the "sh" I'm using is still bash, but bash in "POSIX" mode (which happens if you invoke /bin/sh instead of /bin/bash on systems where /bin/sh is an alias for bash). If this is the case on your system, you can test with:

/bin/bash prog.sh 4
/bin/sh prog.sh 4

This is based on one of the differences explained here: https://www.gnu.org/software/bash/manual/html_node/Bash-POSIX-Mode.html

  • 1
    \$\begingroup\$ How does this work? \$\endgroup\$ Commented Apr 12, 2017 at 19:09
  • 2
    \$\begingroup\$ @BrianMinton Try running kill -l (lists possible signals; doesn't change anything) in bash and sh. It's one of many differences you can find here: gnu.org/software/bash/manual/html_node/Bash-POSIX-Mode.html \$\endgroup\$
    – Dave
    Commented Apr 12, 2017 at 19:16

Python 3 and Python 2, 18 bytes

I took inspiration from this answer

(1/2or 2).__rpow__

Python 3 : Try it online!

1/2 is evaluated to 0.5 so 1/2or 2 is equal to 0.5 => sqrt

Python 2 : Try it online!

1/2 is evaluated to 0 so 1/2or 2 is equal to 2 => ^2


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.