There have been a couple of challenges involving doubling source code: here and here. The task we have here is a bit harder, but should be doable in almost every language.

In this challenge, you will take in an arbitrary positive integer. Your program must output that integer doubled. When your source code is doubled, it will take in a positive integer, and output it squared.

How is your source code doubled? Well, you can have it your way. That is to say, you can split your source code up into strings of bytes or characters (or tokens in tokenized langs) of any equal length you want, and repeat each chunk twice in succession.

For an initial program of ABCDEFGHIJKL, (length 12) here are all possible doubled programs:

Chunk length |   Doubled source code
-------------+-------------------------
1 | AABBCCDDEEFFGGHHIIJJKKLL
2 | ABABCDCDEFEFGHGHIJIJKLKL
3 | ABCABCDEFDEFGHIGHIJKLJKL
4 | ABCDABCDEFGHEFGHIJKLIJKL
6 | ABCDEFABCDEFGHIJKLGHIJKL
12 | ABCDEFGHIJKLABCDEFGHIJKL

Note that this means programs of prime lengths can only be doubled two ways: every character doubled, or the full program is repeated twice.

### Rules:

• Code must be a full program or function.
• Standard loopholes are forbidden.
• Standard I/O methods are allowed.
• All characters/bytes, including whitespace and newlines, are counted in the length of the code and contribute to chunks.
• You may assume that the input and its square can be represented by your language's int/integer type.
• You may not assume a trailing newline or other character.
• Provide your chunk size in the heading after the byte count.
• This is , so shorter programs are better! If two programs are the same length, the one which uses the smaller chunk length wins. (If you have a longer program which uses a smaller chunk length, that is worth posting too!)
• If your program requires a second input/line, you may make no assumptions on its value. In particular, your program should work if the second input is empty, the same as the first, or a different integer. If your program does not require a second input/line, you may ignore this restriction.

## This question has an open bounty worth +100 reputation from Sriotchilism O'Zaic ending in 2 days.

The current answers do not contain enough detail.

I would like to award this bounty to the Brain-Flak answer with the smallest chunk size, with program size only as a tie breaker. If no answer manages to beat my current score I will award it to the Brain-Flak answer that is in my opinion the coolest.

• Can I output result as float (with .0 at the end)? – val Sep 11 at 16:08
• May we print the square twice when the code is doubled? Single code: 5 -> 10; double code: 5 -> 25 25. – Robin Ryder Sep 12 at 7:05
• @RobinRyder No, you may not. – GammaFunction Sep 12 at 7:53
• @val You may output as float. – GammaFunction Sep 12 at 15:28

# Perl 5, 8 bytes (chunk size 4)

$_*=~~+2 Unary ~ is the bitwise negate, so applying it twice is a noop. Thus, the base program simply multiplies$_ (the implicit input-output variable) by 2.

Binary ~~ is smartmatch, which returns a boolean. ~~+2~~+2 parses as (~~+2) ~~ (+2). Since 2 equals 2, this yields true (1). Thus, the doubled program first multiplies $_ by 1, then multiplies$_ by itself.

# 05AB1E, 4 bytes (chunk size 2 or 4)

·Inr
·        # double the implicit input
In      # square the input
r     # reverse the stack: it's now [input ** 2, input * 2]
# if we stop here: implicitly output the top of the stack (input * 2)
·        # double the top of the stack (giving input * 4, not that it matters)
In      # square the input
r     # reverse the stack: it's now [input ** 2, input * 4, input ** 2]
# implicitly the top of the stack (input ** 2)

# Python 3, 26 bytes (chunk size 13)

lambda n:"and n*n#"and 2*n

Try it online!

### Doubled:

lambda n:"andlambda d:"and n*n#"and 2*n n*n#"and 2*n

This solution is provided by @Grimy.

## Python 3, 3230 28 bytes (chunk size 1615 14)

lambda n:bool(0)*n*n or  2*n

Try it online!

-4 bytes thanks to @negativeSeven

### Doubled:

lambda n:bool(lambda n:bool(0)*n*n or  2*n0)*n*n or  2*n

Try it online!

The function takes advantage of the unique chunk rule of this challenge.

• 26: TIO – Grimy Sep 10 at 21:19
• @Grimy Nice approach. I think it is different enough and deserves its own post. – Joel Sep 10 at 23:47
• @Grimy I added your solution to my post since you do not seem to be interested in making a separate post. – Joel Sep 13 at 2:25

# Befunge-98 (FBBI), 8 bytes (chunk length 2)

;&:#* +q

Try it online!

;&;&:#:#* * +q+q

Try it online! (doubled)

Excluding control flow, the first program executes &:+q (input, duplicate top of stack, add, exit with return code), and the second executes &:*+q (input, duplicate top of stack, multiply, add (sums with an implicit 0), exit with return code)

# Hexagony, 14 bytes (chunk size 14)

?"+==*/}=+!@!<

? " +
= = * /
} = + ! @
! < . .
. . .

Try it online!

## Doubled

?"+==*/}=+!@!<?"+==*/}=+!@!<

### Expanded:

? " + =
= * / } =
+ ! @ ! < ?
" + = = * / }
= + ! @ ! <
. . . . .
. . . .

Try it doubled online!

Hexagony is in a bit of a weird position in this challenge, in that actually achieving the task is not much more difficult than simply being able to write the two individual programs. However, golfing the solution proved rather difficult.

This solution is the trivial idea in the shortest form that I could fit, but I suspect there are shorter, cleverer answers. This version very naively sets two values to the input and sums them or multiplies them, depending on if the source is doubled. The only code reuse is the "+ which makes making the copy code for the doubled program short enough to fit in the unused space from the original program.

I suspect using the IP change instructions [] will make isolating the parts easier, but a truly ideal solution will reuse a lot of code between the two. I made a helper program to double hexagony source code. Note that it removes trailing no-ops so if you want to have placeholder no-ops at the end just fill in some other character and change it back after. It can handle different chunk sizes, though I didn't yet write code to output each possible program (Hexagony seems to lend itself to using the full chunk size).

• @JoKing Well done! It's rather different from my answer, so would you want to post it (using the different chunk size to fill up unused space is really neat!)? Otherwise I'll add it and an explanation when I have more time. – FryAmTheEggman Sep 12 at 2:55

# Hexagony, 12 bytes (chunk size 4)

?"2+...}=*!@

Try it online!

Formatted:

? " 2
+ . . .
} = * ! @
. . . .
. . .

And doubled, then formatted:

? " 2 +
? " 2 + .
. . } . . .
} = * ! @ = *
! @ . . . .
. . . . .
. . . .

Basically, this sets the first edge to the input, then the second edge to either 2 or a copy of the input, then multiplies those two edges into the third edge, prints that and terminates. The list of executed instructions are just

?"2}=*!@

and

?"2+}=*!@

With the only difference being the + overriding the 2 on the second program.

# JavaScript (ES6),  24  22 bytes

Despite its unusual format, this is the definition of an anonymous function, which can be either called directly or assigned to a variable.

+(g=x=>x*x)?g:(x=>x*2)

Try it online!

+(g=x=>x*x)?g:(x=>x*2)+(g=x=>x*x)?g:(x=>x*2)

Try it online doubled!

### How?

Applying the unary + to a function is interpreted as an attempt to coerce it to a number and results in NaN. Therefore, the leading +(g=x=>x*x) is falsy in both versions.

On the other hand, applying the binary + between 2 functions results in a string. Therefore, (x=>x*2)+(g=x=>x*x) is truthy in the doubled version.

# Perl 6, 8 bytes (chunk size 1)

* *<1 2>

A Whatever/HyperWhatever lambda that takes a number and returns a number for the first program and a singleton list for the second program. Basically this keeps the exact same logic, except that the multiplication operator (*) is replaced by the exponential one (**).

**  **<<11  22>>

The Whatever literal (confusingly also represented by a *) are doubled up to a HyperWhatever (**) which is basically the same except it maps over lists. The space is needed to separate the Whatever literal from the multiplication and is ignored when doubled up. Instead of just 2 (which would get doubled to 22) we use a list containing two elements, which evaluates to 2 in a numeric context). The <> can be doubled to a list with interpolation, and the two elements inside are doubled, but neither of those change the length of the list.

# Runic Enchantments, 9 bytes (chunk size 3)

i3?:*@:+@

The 3? skips the next 3 instructions, resulting in an (executed) i3?...:+@. When doubled it results in an executed i3?...:*@ where . represents the 3 NOP'd instructions. @ is "print entire stack and terminate."

# C# (Visual C# Interactive Compiler) / Javascript, 22 bytes, chunk size 11

m=>/*      /2*m//*/m*2

Try it online!

• Also works in JavaScript – Shaggy Sep 10 at 21:24
• Also works in Java by changing the = to -. Nice answer! – Kevin Cruijssen Sep 11 at 6:27
• I like how the comment actually describes what the code does. :p – Arnauld Sep 11 at 7:50

# Brain-Flak, 76 bytes, 76 byte chunks

({}<>)(()[([][()])]{(<{}{}({({})({}[()])}<>)<>>)}{}){{}(({})({})<>)(<>)}{}<>

Try it online!

## Doubled (with newline for clarity)

({}<>)(()[([][()])]{(<{}{}({({})({}[()])}<>)<>>)}{}){{}(({})({})<>)(<>)}{}<>
({}<>)(()[([][()])]{(<{}{}({({})({}[()])}<>)<>>)}{}){{}(({})({})<>)(<>)}{}<>

Try it online!

Here is a version that uses a more complex doubling procedure. It does 5 chunks of size 15. The code here is 46 bytes however due to the required padding it is substantially longer.

# 105 90 bytes, 15 byte chunks

(              {<><({}()())><><><            <>>({})({}[()])}{}            )<>

Try it online!

## Doubled (with newlines for clarity)

(              (
{<><({}()())><>{<><({}()())><>
<><            <><
<>>({})({}[()])<>>({})({}[()])
}{}            }{}
)<>            )<>

Try it online!

# Cubix, 18 14 bytes (chunk length 9 7)

*OI$|:/@O+:I. Note the trailing space. Try it online! Doubled: *OI$|:/*OI$|:/@O+:I. @O+:I. Again, there is one trailing space. Try it online! ## Explanation The main idea is that doubling the code causes the cube to become bigger, so the instruction pointer starts at a different symbol. Since the addition program cannot be put on a cube of side length 1, the side length is going to be 2. Additionally, the doubled code needs to be on a cube of side length 3, so the doubled code must be at least 25 bytes. This means the code must be at least 13 bytes long. As such, at most 1 more byte can be saved. Now to the actual code. The first observation is that the top face (that is, the first 4 characters) are not used by the addition program. Furthermore, if we make the 5th character reflect the IP around the cube, we can free up 2 more characters. We will use these characters to put the squaring program. # R, 59 30 bytes (chunk size 59 30) F=F+1;f=function(n)n*c(2,n)[F] Try it online! Credit to Robin Ryder for inspiring this; increments F each time, and the function f selects the appropriate output. This isn't particularly interesting, but doubtless something clever manipulating the chunk size will be dreamed up. # Brain-Flak, 48 30 bytes (chunk size 10) (({}))<>( {({}[()])}{}<>{}{}) This basically takes three steps, then when doubled executes those steps twice each. The initial program is: 1. Duplicate TOS, switch stacks and start pushing a value 2. Get the TOS's triangular number n*(n-1)/2 3. Pop TOS, switch stack and pop twice, then push the result. For an input n into an undoubled program, this results in: 1. Start stack: n n Other stack: < Third stack: 2. Start stack: n n Other stack: 0 < Third stack: tri(0) = 0 3. Start stack: n+n+tri(0) = 2n < Other stack: Third stack: For the doubled program: 1a. Start stack: n n Other stack: < Third stack: 1b. Start stack: n n < Other stack: 0 0 Third stack: 2a. Start stack: n 0 < Other stack: 0 0 Third stack: tri(n) 2b. Start stack: n 0 < Other stack: 0 0 Third stack: tri(n)+tri(0) = tri(n) 3a. Start stack: n Other stack: tri(n) < Third stack: tri(n) 3a. Start stack: 0+n+tri(n)+tri(n) = n + 2*tri(n) = n + n*(n-1) = n*n < Other stack: Third stack: # JavaScript (Node.js), 15 12 bytes (chunk size: 6) x=>/**/2*(x) Try it online! Single case: x=>/**/2*(x) Double case: x=>/**x=>/**/2*(x)/2*(x) Seems to also work in C#, and Java if changing => to ->? # R, 4235 28 bytes (chunk size 4) Now with a smaller chunk and no error. I also have a longer solution with chunk size 3; see below. I don't think it is possible to write an R answer with chunk size 1 or 2; I'll happily give a bounty to anyone who proves me wrong. s =scan# n=s()# n/2*4# Try it online! The # is for comments in R. The 3rd line is only spaces, making a chunk of newline + 2 spaces + newline, so that the previous and next chunk can have no newline. Doubled, it becomes: s =ss =scan#can# n=s n=s()# ()# n/2*n/2*4# 4# Try it online! The single version computes $$\\frac n2\times4=2n\$$; the double version computes $$\\frac n2\times \frac n2\times4=n^2\$$. Here is a slightly longer solution, but with chunk size 3: # R, 39 bytes (chunk size 3) s =bbb=scan# n=s(# )# n* 1/ 2/ 1* 4# Try it online! Doubled: s =s =bbbbbb=sc=scan#an# n= n=s(#s(# )# )# n* n* 1/ 1/ 2/ 2/ 1* 1* 4# 4# Try it online! Note that Giuseppe has another R answer, with one chunk of 30 bytes. # Perl 5 (-p), 22 15 bytes -7 bytes thanks to Grimy$_*=$'/4||2;//; TIO • 15: TIO – Grimy Sep 10 at 13:39 • looking at your solution, I'd just found a 22 bytes solution – Nahuel Fouilleul Sep 10 at 13:42 • understood, first input*=2, then by input*=input/4 – Nahuel Fouilleul Sep 10 at 13:44 • another 16 bytes (-a)$_*=/@F/?2:$_/4; – Nahuel Fouilleul Sep 10 at 13:58 • Down to 8 (posted as a separate answer since it's very different). – Grimy Sep 10 at 13:59 # Charcoal, 13 bytes ＰＩ×Ｉθ⎇υＩθ²⊞υω Try it online! Explanation: The predefined empty list is falsey so the input is multiplied by 2. When doubled the second pass sees the empty string has been pushed to the list so it multiplies the input by itself instead. Try it online! In verbose syntax this corresponds to Multiprint(Cast(Times(Cast(q), Ternary(u, Cast(q), 2)))); Push(u, w);. # Python 3, 56 53 bytes print(eval(input()+"**2"[len(*open(__file__))%2:])) # My python skills kinda suck, so can definitely be golfed.. Based on the Python answer in the "I double the source, you double the output!" challenge. Chunk length 53. # Java 8, 62 bytes n->n*(Byte.SIZE>8?n:2);/* class Byte{static int SIZE=9;}/**/// Chunk length 62. Explanation: n-> // Method with integer as both parameter and return-type n* // The input, multiplied by: (Byte.SIZE>8? // If Byte.SIZE is larger than 8: n // Multiply by the input itself : // Else: 2); // Multiply by 2 class Byte{ // Class which overwrites Byte static int SIZE=9;} // And sets the SIZE to 9 In Java, the available comments are // comment and /* comment */. Which are combined here to overwrite certain parts. See how these comments work thanks to the Java highlighting: n->n*(Byte.SIZE>8?n:2);/* class Byte{static int SIZE=9;}/**/// n->n*(Byte.SIZE>8?n:2);/* class Byte{static int SIZE=9;}/**///n->n*(Byte.SIZE>8?n:2);/* class Byte{static int SIZE=9;}/**/// The doubled program created a custom Byte class and its value SIZE=9, which overwrites the default java.lang.Byte class and its value SIZE=8. # Japt, 7 5 bytes *N²jJ ² pushes 2 to the array of inputs N then j removes & returns the element at index J=-1 (i.e., the newly inserted 2) and multiplies the input by that. When doubled it results in J being multiplied by 2, so the element at index -2 (i.e., the input) is returned by j and used as the multiplier. # Jelly, 8 6 bytes (chunk length 3) Ḥ;²3ị Try it online! Doubled # Nice solution: Lua, 66 bytes (chunk size 66 bytes) a,x=a and...^2 or ...*2,setmetatable(x or{},{__gc=load'print(a)'}) Try it online! (double it yourself, it is not so hard) Oh yeah, pretty sure that there is shorter solution to this, but it's the best I was able to came up with this way. Take input as first argument. Brief explanation: whole business with a is quite obvious for everyone, while the second part with x is more interesting. Basically, I create a table (or update existing one on second pass) with finalizer (__gc metamethod) which gets called when program exits. # Lame solution: Lua, 60 bytes (chunk size 30 bytes) a=a and...^2 or ...*2; print(a)os.exit() Smaller and with better chunking, but ultimately boring and lame without any clever tricks. I'm pretty sure no comments are required to this one. # J, 1510 9 bytes +: :(*-:) Try it online! Doubled version: Try it online! f : g creates a verb that executes f when called with one argument, and g when called with 2 arguments. So ours executes double +: with the original source and *-: when the source is doubled. This works because a train of two verbs in J becomes a hook, and thus f f is executed as y f (f y) where y is the original input. Additionally, *-: is itself a "dyadic hook" which works by multiplying * the left arg by half -: the right arg. The left arg will be the original input, and the right arg will be the input doubled, so this will produce the square of the original input. ## original answer ## J, 15 bytes *:@]`(+:@])@.=~ Try it online! Doubled version: Try it online! In the single version, we have a single verb which uses Agenda @. to do the if... then logic: If the argument is equal to itself =~, then take the argument and double it (+:@[). However, when we double the code, we get a J hook. Call the verb f and the input y. Then the hook f f executes like this: y f (f y) Which means that now the original input is the left arg, and the right arg is the doubled input. Since these will not be equal, =~ will return false this time, and now we'll execute the other fork of the Agenda, ie, *:@], which means "square the right arg." And since ~ reverses the inputs of a dyadic verb, the right arg will be the original input. # PowerShell, 22 bytes (chunk size 11) param($p)
#   /
2 * $p Doubled: param($p)
#param($p) # / 2 *$p   /
2 * $p This solution is based on @ShieruAsakoto's solution. @Grimy solution that has been converted to PowerShell, 26 bytes (chunk size 13) param($p)$t=';$p*$p#';$p*2

Doubled:

param($p)$t=';param($p)$t=';$p*$p#';$p*2$p*$p#';$p*2
• Unfortunately you need to have a chunk size that divides your code into equal chunks. As per example in question about prime length solutions. – John Rees 6 hours ago
• @JohnRees, i corrected my answer, thanks. – Andrei Odegov 6 hours ago