Calculate a square and a square root!

49

5

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.

programmer5000

Posted 2017-04-11T18:05:26.677

Reputation: 7 828

Answers

45

Jolf and MATL, 1 byte

U

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.

Rɪᴋᴇʀ

Posted 2017-04-11T18:05:26.677

Reputation: 7 410

90

C and C++, 68 65 bytes

#include<math.h>
float f(float n){auto p=.5;return pow(n,2-p*3);}

Original answer:

#include<math.h>
float f(float n){return pow(n,sizeof('-')-1?2:.5);}

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

Dave

Posted 2017-04-11T18:05:26.677

Reputation: 7 519

23+1 as a "Ha!" for all those people who treat C and C++ as the same thing. – DocMax – 2017-04-11T22:19:04.923

How does C interpret this to get n^2? Does p get set to 0? I'm reading it like C++ would and have no idea how C interprets it differently. – CAD97 – 2017-04-12T01:28:04.907

20@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. – None – 2017-04-12T01:46:20.847

2This is brilliant. – Quentin – 2017-04-12T08:23:07.330

How is sizeof('-') interpreted differently in C and C++? Is '-' an int in C? – YSC – 2017-04-12T08:55:23.263

@YSC It does seem like that's the case for C, for C++ it's 1 indeed

– Gizmo – 2017-04-12T09:58:55.283

1

Found a Stack Overflow question about it.

– YSC – 2017-04-12T10:47:12.943

Been writing C for donkey's years, never seen "auto" before. Awesome. – Wossname – 2017-04-12T13:44:55.423

9I think the explanation for this answer would be improved by editing in @ais523's comment explaining why C produces n^2. – Brian J – 2017-04-12T14:59:17.357

@BrianJ normally I put a full explanation in my answers, but in this case I found so many unexpected differences between the languages that I think it's more interesting for people to look up what's going on for themselves and stumble across some of the others. – Dave – 2017-04-12T18:42:58.567

The repurposing of auto in C++ was introduced in 2011. For all C++ standards before 2011, the version using auto would produce the same in both C and C++. The sizeof version works for all C and C++ standards. – Peter – 2017-04-14T06:36:00.773

What about #include<math.h> #define f(n) pow(n,sizeof('-')*1.5-1)? It seems to be shorter than both. Or do codegolf rules recommend using functions instead of preprocessor macros? – Sasha – 2017-04-14T14:42:01.160

1@Sasha sizeof('-')*1.5-1 wouldn't work unless the machine has a 16-bit int: it gives 5 if int is 32-bit or 11 if int is 64-bit. As for using macros rather than functions, you'd have to check meta for confirmation, but I haven't seen it done. – Dave – 2017-04-14T15:07:54.457

@Dave, you're right. Then #include<math.h> #define f(n) pow(n,sizeof('-')>1?2:.5). It's anyway shorter. – Sasha – 2017-04-14T16:43:45.267

sizeof doesn't need parentheses, so the longer version could just be sizeof'-'-1?... (or indeed with >), but that's still longer than the auto version. – hvd – 2017-04-15T20:27:15.123

50

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!

Dave

Posted 2017-04-11T18:05:26.677

Reputation: 7 519

this is so cool! – njzk2 – 2017-04-12T18:13:24.073

Why? Is it the lack of space before or? – chx – 2017-04-14T01:11:22.253

@chx In Py2, / does integer division (1/2==0). In Py3, it does floating point division (1/2==0.5). 0 is falsey. – Fund Monica's Lawsuit – 2017-04-14T03:04:56.937

then why not remove the space after or? – chx – 2017-04-14T03:09:41.643

@chx Try it yourself. It throws a syntax error if you do. – numbermaniac – 2017-04-14T03:25:45.270

@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. – Rɪᴋᴇʀ – 2017-04-27T14:44:36.350

32

2sable / Jelly, 2 bytes

*.

2sable computes the square. Try it online!

Jelly computes the square root. Try it online!

How it works

2sable

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

Jelly

 .  Numeric literal; yield 0.5.
*   Raise the input to the power 0.5.
    This yields the square root.

Dennis

Posted 2017-04-11T18:05:26.677

Reputation: 196 637

7It's like these languages were created just for this challenge – FloatingRock – 2017-04-12T10:10:46.550

20

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.

Comrade SparklePony

Posted 2017-04-11T18:05:26.677

Reputation: 5 784

@Riker Will do, thank you. – Comrade SparklePony – 2017-04-11T18:34:35.063

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

– Delioth – 2017-04-13T20:08:59.480

@Delioth It actually made more sense just to use the function, and wipe out the io. – Comrade SparklePony – 2017-04-13T20:26:37.740

Oh, yeah- much better. Do you even need to include stdio.h in that case? – Delioth – 2017-04-13T20:29:32.283

@Delioth I don't. Whoops! – Comrade SparklePony – 2017-04-13T20:31:42.550

16

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                                  ...

Jelly

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.

Ohm

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.

Business Cat

Posted 2017-04-11T18:05:26.677

Reputation: 8 927

Nice! The byte count is fine. – programmer5000 – 2017-04-11T18:32:32.033

I edited my answer to 5 bytes because of this as well, good catch. – Magic Octopus Urn – 2017-04-11T18:33:37.560

Wow, the first Ohm answer not written by me! Well done! – Nick Clifford – 2017-04-11T18:33:53.537

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. – AdmBorkBork – 2017-04-11T18:34:27.510

Both of those chars are in Jelly's code page and in Ohm's codepage it should seem... So those count as single bytes. If you don't need the space and the newlines I agree with @AdmBorkBork – Magic Octopus Urn – 2017-04-11T18:35:52.363

@AdmBorkBork Are you saying I should take Ohm's codepoint for ² and use the Jelly character at that codepoint? (or vice versa) – Business Cat – 2017-04-11T18:36:38.073

1I'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. – AdmBorkBork – 2017-04-11T18:40:34.083

@NickClifford I did one too. http://codegolf.stackexchange.com/a/112657/56341

– Roman Gräf – 2017-04-12T06:47:22.183

@RomanGräf Whoa, you've really been using the language a lot! Guess I'm just blind or something :P – Nick Clifford – 2017-04-13T02:09:33.790

15

C89 and C99, 47+3 = 50 bytes

float f(float n){return n//*
/sqrt(n)//*/1*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.

Dave

Posted 2017-04-11T18:05:26.677

Reputation: 7 519

13

Octave / MATLAB, 31 29 bytes

 @(x)x^(2-3*any(version>60)/2)

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

Explanation:

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, 
                                       % '9.2.0.538062 (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')

Stewie Griffin

Posted 2017-04-11T18:05:26.677

Reputation: 43 471

12

Basic / Delphi – 6 characters

sqr(x)

Square root in Basic and square in Delphi.

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

user15259

Posted 2017-04-11T18:05:26.677

Reputation:

2Does this take input by itself? – Rɪᴋᴇʀ – 2017-04-12T17:31:33.377

No, but neither do some other submissions, including the C/C++ one. – None – 2017-04-13T02:53:06.037

Still invalid though, that doesn't change anything. I'll try to comment on those also. – Rɪᴋᴇʀ – 2017-04-13T03:05:49.007

1Can 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. – Rɪᴋᴇʀ – 2017-04-13T03:21:11.133

sqr is a function as well, and takes a parameter. It happens to be built-in like some of the golfing languages. – None – 2017-04-13T10:19:21.230

3Yes, 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. – Rɪᴋᴇʀ – 2017-04-13T12:59:23.620

11

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 ;)

Okx

Posted 2017-04-11T18:05:26.677

Reputation: 15 025

105AB1E and Fireball use different encodings. Does this affect the programs? – Dennis – 2017-04-11T18:32:03.300

@Dennis I didn't think about that. So saving the same program in different encodings doesn't count for polygots? – Okx – 2017-04-11T18:34:31.597

5Afaik, the default is that the byte streams must match. – Dennis – 2017-04-11T18:37:41.963

10

PHP7 + JavaScript, 62 61 58 bytes

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

eval(['alert((_=prompt())*_)','echo$argv[1]**.5'][+![]]);

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

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

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!

Ismael Miguel

Posted 2017-04-11T18:05:26.677

Reputation: 6 797

1![] will save you 1 byte :-) – rckd – 2017-04-12T15:25:57.703

1@rckd Holy cow! Totally forgot about empty arrays. Thank you! I've edited into the question, with an explanation on how it works. – Ismael Miguel – 2017-04-12T16:05:32.177

1you can save 3 bytes by using echo$argv[1]**.5 rather than echo sqrt($argv[1]) – user59178 – 2017-04-13T11:34:55.717

Wow, nice saving! Thank you! I've added it into the answer. – Ismael Miguel – 2017-04-13T12:35:39.507

8

05AB1E and Jelly, 4 bytes

nqƓ½

(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:

nq“\n

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

nqƓ½

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

Magic Octopus Urn

Posted 2017-04-11T18:05:26.677

Reputation: 19 422

2This 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. – Dennis – 2017-04-11T18:37:12.510

@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. – Magic Octopus Urn – 2017-04-11T18:47:30.980

1Scoring 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. – Dennis – 2017-04-11T18:52:54.190

4@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. – Dave – 2017-04-12T07:20:35.577

@Dave I must've misinterpreted Dennis then. – Magic Octopus Urn – 2017-04-12T13:42:31.973

It's actually 4 bytes, you can remove 6 bytes entirely from the header. The byte stream is 6e 71 93 0a. – Erik the Outgolfer – 2017-04-14T14:14:37.327

6

CJam / MATL, 8 bytes

ld_*GX^!

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

Luis Mendo

Posted 2017-04-11T18:05:26.677

Reputation: 87 464

Hey! Nice submission! Care to add an explanation like other answers? – programmer5000 – 2017-04-12T00:56:16.963

@programmer5000 I fixed an error and added the explanations – Luis Mendo – 2017-04-12T01:23:21.847

5

PHP and CJam, 30 29 25 bytes

ECHO"$argv[1]"**2;#];rdmq

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

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!

CJam

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!

Business Cat

Posted 2017-04-11T18:05:26.677

Reputation: 8 927

5

Python 2 and Forth, 43 33 bytes

( """ )
fsqrt
\ """);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:

3141e-3

mbomb007

Posted 2017-04-11T18:05:26.677

Reputation: 21 944

5

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

f=a=>eval(`try{eval("a**2")}catch(e){Math.sqrt(a)}`)

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.

f=a=>eval(`try{eval("a**2")}catch(e){Math.sqrt(a)}`)

console.log(f(4));

Tom

Posted 2017-04-11T18:05:26.677

Reputation: 3 078

Clever! Nice job on this one! – programmer5000 – 2017-04-12T13:12:41.537

Is there a reason for the backticks? Seems like single quotes would do the job. – JLRishe – 2017-04-12T15:54:33.893

@JLRishe Nope, no reason :) – Tom – 2017-04-12T16:31:11.210

5

C, Operation Flashpoint scripting language, 52 bytes

;float f(float x){return sqrt(x);}char*
F="_this^2";

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.

C:

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

Steadybox

Posted 2017-04-11T18:05:26.677

Reputation: 15 798

Okay, this is pretty cool. How'd you think of using that scritping lang? – Rɪᴋᴇʀ – 2017-04-17T20:00:31.137

@Riker Operation Flashpoint always was one of my favorite games; I used to do lots of stuff in it with its scripting language. – Steadybox – 2017-04-17T20:48:59.890

3

QBIC / QBasic, 26 18 bytes

input a
?a^2'^.25

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 goed 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.

steenbergh

Posted 2017-04-11T18:05:26.677

Reputation: 7 772

3

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

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

:*n;
½

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

steenbergh

Posted 2017-04-11T18:05:26.677

Reputation: 7 772

Are you allowed to not use the -v in jelly too? – Rɪᴋᴇʀ – 2017-04-12T17:30:56.173

The use of -v is, in my opinion, in line with the [top-voted answer[(https://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.

– steenbergh – 2017-04-13T09:43:57.047

3

Reticular / Befunge-98, 15 bytes

2D languages!

/&:*.@
>in:o#p;

Befunge-98

/&:*.@

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

Reticular

/           mirror up, then right
>in:o#p;

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

Conor O'Brien

Posted 2017-04-11T18:05:26.677

Reputation: 36 228

3

Python 3 + JavaScript, 101 bytes

0//1or exec("function=lambda a:(lambda b:a);x=0")
y=2//2/2
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.

kjaquier

Posted 2017-04-11T18:05:26.677

Reputation: 131

Tested on Firefox and it is working. Is it possible to use x=>x**y instead? Or Python will choke on that? – Ismael Miguel – 2017-04-12T16:06:29.663

@IsmaelMiguel python doesn't support arrow functinos. – Rɪᴋᴇʀ – 2017-04-13T03:16:25.893

This doesn't work for python. Function isn't a keyword. – Rɪᴋᴇʀ – 2017-04-13T03:16:48.563

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). – kjaquier – 2017-04-18T10:11:58.220

3

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

Dave

Posted 2017-04-11T18:05:26.677

Reputation: 7 519

1How does this work? – Brian Minton – 2017-04-12T19:09:00.990

2

@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: https://www.gnu.org/software/bash/manual/html_node/Bash-POSIX-Mode.html

– Dave – 2017-04-12T19:16:40.277

2

Jelly / Pip, 6 bytes

EDIT: It's a byte shorter to reverse operations.

RTa
²

Try Jelly online!

Jelly starts execution at the bottom of the code (its 'main link') and sees if it needs anything higher: it sees the command to square and takes care of input and output implicitly.

Try Pip online!

Pip executes the top line, squaring the (implicitly read from the cmd line) var a and implicitly prints that. The bottom line is ignored.

steenbergh

Posted 2017-04-11T18:05:26.677

Reputation: 7 772

Alternative 6-byter: PRTaVS. – steenbergh – 2017-04-12T08:32:49.180

2

Wolfram Language / PHP, 25 bytes

Get the square of a number in Wolfram Language and get the square root in PHP;

n^2
echo sqrt(_GET["n"]);

First line is Wolfram Language. First, you are the ones to change n in the searchbar in Wolfram Alpha so the code is also the input. Then it's will generate the answer upon pressing enter

n^2

Second line is PHP, It gets the square root of the n which is to be inputted in the address bar (eg. ppcg.php.net?n=213, where 213 is n's value)

echo sqrt($_GET["n"]);

Jimwel Anobong

Posted 2017-04-11T18:05:26.677

Reputation: 159

1

Welcome to PPCG! However, you must take input somehow. You can't assume the number is stored in a variable. Sorry about that. You can view the list of acceptable i/o methods here. (positive scores on the answers mean it's allowed, negative means not allowed)

– Rɪᴋᴇʀ – 2017-04-12T16:15:33.083

Got it. I'll just edit my answer. :) Another thing, I'll just explain why adding another code for input in wolfram is not applicable. – Jimwel Anobong – 2017-04-12T16:18:09.423

Happy to help! Hope you stick around in ppcg! – Rɪᴋᴇʀ – 2017-04-12T16:21:53.993

Wolfram|Alpha is not a valid language. – ngenisis – 2017-04-12T22:59:23.090

1Wolfram Language is based on mathematica which needs mathematical formula to be type in a non-natural way. Another thing, the answerer clears it out, its the website that's not the language but the wolfram language is the language that supports it. Wolfrsm Language and WolframAlpha is related to each ofher but not the same. The'yre totally different. – Jimwel Anobong – 2017-04-13T02:36:19.137

2

PHP 5.6 and PHP 7, 55 bytes

function f($n){list($a[],$a[])=[.5,2];echo $n**$a[0];}

PHP 5.6 produces n^2, PHP 7 produces sqrt(n).

Dave

Posted 2017-04-11T18:05:26.677

Reputation: 7 519

2

macOS Bash and sh, 24 bytes

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

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.

Digital Trauma

Posted 2017-04-11T18:05:26.677

Reputation: 64 644

Nice use of a different mode/ env! – programmer5000 – 2017-04-12T23:29:28.387

This is much better than my version! – Dave – 2017-04-13T06:55:25.890

1

Octave / Cardinal, 28 bytes

This program squares the input in Cardinal and gets the square root in Octave

 %:=t.
disp(sqrt(input("")))

Try it online! (Octave)

Try it online! (Cardinal)

So % is single line comment in Octave so it just gets input and prints the square root

disp(sqrt(input("")))

So that the Cardinal program doesn't encounter a divide by 0 error and die, the program

%:=t.

has been shifted with a space, which is ignored by both programs

Explanation of the Cardinal program:

The program starts at the %
It receives input and stores the value as active :
It sets the inactive to be equal to the active =
It multiplies the active by the inactive t
Finally it outputs the active value .

fəˈnɛtɪk

Posted 2017-04-11T18:05:26.677

Reputation: 4 166

1

PHP / JavaScript, 43 bytes

<body onload=alert(<?=$x*$x.')>'.sqrt($x)?>

Input goes like:

<?php $x = 10; ?>

Kinda self-explaining, but does it fit the rules? My first code golf tho :-)

rckd

Posted 2017-04-11T18:05:26.677

Reputation: 111

1Welcome to code golf! Input must be a float or a string that is only a float. If I understand correctly, this requires separate input. – programmer5000 – 2017-04-12T13:39:58.870

Are you sure this runs as JavaScript? It looks like both versions need a PHP processing stage (JavaScript wouldn't know what to do with alert(<?=$x*$x.')>'.sqrt($x)?) – Dave – 2017-04-12T19:26:03.417

0

CGL (CGL Golfing Language) / JS (ES6), 13 bytes(non-competing)

Non-competing because:

  1. CGL was released after this question.
  2. CGL is not a valid language. Because of and , CGL is technically a valid language.

Code:

 x=>x**2
//-₂

JS:

Simple: an anonymous arrow function that returns its first argument squared. The unnamed language code is commented out.

CGL:

The non-breaking space before the first line acts like a comment. The /s are no-ops. The - in the second line means to decrement the current stack number, which by default is 0. That then sets it to -1, where input is stored. The replaces the first item in the current stack with its square root, which is now where input is placed. By default, the current stack is outputted, outputting the square root of the input.

programmer5000

Posted 2017-04-11T18:05:26.677

Reputation: 7 828

This is 13 bytes. I dunno about CGL, but I'm fairly certain JS uses ascii/utf-8. CGL would probably also use UTF-8, unless it has it's own codepage. – Rɪᴋᴇʀ – 2017-04-13T18:46:25.490

@Riker for now, it uses ascii/utf-8. Thanks. – programmer5000 – 2017-04-13T19:28:24.550