I double the source, you double the output!

Your task, if you wish to accept it, is to write a program that outputs a positive integer (higher than 0). The tricky part is that if I duplicate your source code, the output must be double the original integer.

Rules

• You must build a full program. That is, your output has to be printed to STDOUT.

• The initial source must be at least 1 byte long.

• Both the integers must be in base 10 (outputting them in any other base or with scientific notation is forbidden).

• Your program must not take input (or have an unused, empty input).

• Outputting the integers with trailing / leading spaces is allowed.

• You may not assume a newline between copies of your source.

• This is , so the shortest (original) code in each language wins!

• Default Loopholes apply.

Example

Let's say your source code is ABC and its corresponding output is 4. If I write ABCABC instead and run it, the output must be 8.

This uses uses @manatwork's layout.

/* Configuration */

var QUESTION_ID = 132558; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 8349457; // This should be the user ID of the challenge author.

/* App */

return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

jQuery.ajax({
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(a) {
var id = +a.share_link.match(/\d+/);
});
if (!data.has_more) more_answers = false;
comment_page = 1;
}
});
}

jQuery.ajax({
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(c) {
if (c.owner.user_id === OVERRIDE_USER)
});
else process();
}
});
}

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(-?\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
return a.owner.display_name;
}

function process() {
var valid = [];

var body = a.body;
if(OVERRIDE_REG.test(c.body))
body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
});

var match = body.match(SCORE_REG);
if (match)
valid.push({
user: getAuthorName(a),
size: +match[2],
language: match[1],
});

});

valid.sort(function (a, b) {
var aB = a.size,
bB = b.size;
return aB - bB
});

var languages = {};
var place = 1;
var lastSize = null;
var lastPlace = 1;
valid.forEach(function (a) {
if (a.size != lastSize)
lastPlace = place;
lastSize = a.size;
++place;

.replace("{{NAME}}", a.user)
.replace("{{LANGUAGE}}", a.language)
.replace("{{SIZE}}", a.size)

var lang = a.language;
if (! /<a/.test(lang)) lang = '<i>' + lang + '</i>';
lang = jQuery(lang).text().toLowerCase();

languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link, uniq: lang};
});

var langs = [];
for (var lang in languages)
if (languages.hasOwnProperty(lang))
langs.push(languages[lang]);

langs.sort(function (a, b) {
if (a.uniq > b.uniq) return 1;
if (a.uniq < b.uniq) return -1;
return 0;
});

for (var i = 0; i < langs.length; ++i)
{
var language = jQuery("#language-template").html();
var lang = langs[i];
language = language.replace("{{LANGUAGE}}", lang.lang)
.replace("{{NAME}}", lang.user)
.replace("{{SIZE}}", lang.size)
language = jQuery(language);
jQuery("#languages").append(language);
}

}
body { text-align: left !important}

width: 290px;
float: left;
}

#language-list {
width: 290px;
float: left;
}

font-weight: bold;
}

table td {
}
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/Sites/codegolf/all.css?v=617d0685f6f3">
<tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>

</tbody>
</table>
</div>
<div id="language-list">
<h2>Winners by Language</h2>
<table class="language-list">
<tr><td>Language</td><td>User</td><td>Score</td></tr>
<tbody id="languages">

</tbody>
</table>
</div>
<table style="display: none">
</tbody>
</table>
<table style="display: none">
<tbody id="language-template">
</tbody>
</table>

• @Mr.Xcoder Then I'll just have to include one in my own source. – steenbergh Jul 15 '17 at 17:55
• @Mr.Xcoder I think that you should have prevented reading your own source code. – caird coinheringaahing Jul 15 '17 at 18:09
• It only needs to work when doubled once? We don't need to support n many doublings? – Cody Gray Jul 16 '17 at 8:36
• @Daniel Let's say your source is  (empty program) and it produces 5. If you double it, your source is  (empty program) and that produces 5 as well, no matter what you do. That being said, an empty program duplicated is still the empty program, and always produces the same output, except for the case where the empty program means something else (a random number generator, for example), which could not be valid anyway. – Mr. Xcoder Jul 17 '17 at 9:11
• This shouldn't be hard for esolangs that automatically dump the top of stack upon program termination. – MD XF Jul 18 '17 at 22:26

Python 3, 33 bytes

Cheating a little:

id=print('\r',1+(not id),end='');
• On a full console, you should only see 1 or 2; or did you mean that the whole output stream contains more than the number itself? (I'm not sure how this behaves in Windows, but on Debian or a Mac, this looks like a single output). – lungj Jul 22 '17 at 19:38
• Oh, yeah, I did a test in TIO before and saw that it didn't work there. In a console, the \r gives a carriage return, but not a newline. Thus, when the second copy of the code is run, it actually starts overwriting the content from the first copy of the code. – lungj Jul 22 '17 at 19:43

Rust, 62 bytes

fn main(){let a=include_str!("a.");print!("{}",a.len()-1)}//

What's happening is the file is including itself as a string during compiletime, and getting the length of itself.

When appended, the extra code is commented out, but still effects the length of the file.

Only works if the file name is 'a.'

Secondary Solution, 63 bytes

fn main(){let a=include_str!(file!());print!("{}",a.len()-1)}//

This solution doesn't use a hardcoded filename, losing 1 byte.

• If the file name is needed, then you have to add the file name to the bytecount. Meta post – Jo King Feb 11 '18 at 22:01
• Done. I still gain a byte. ^_^ (I'd remove the dot, but otherwise rustc complains) – moonheart08 Feb 12 '18 at 2:28

Underload, 1513 8 bytes

-2 thanks to Martin Ender

-5 thanks to Ørjan Johansen

(1)\r2)S(

The \r in the code should be a literal carriage return character.

There's no way for spec-complaint Underload to actually solve this challenge. This submission uses several tricks to do it:

• stringie, the TIO interpreter, ignores unmatched close brackets and segfaults on unmatched open brackets, which is allowed.
• Using \r allows us to overwrite whatever has already been output with new output. This requires a terminal for which \r clears the line, rather than just allowing it to be overwritten with new text.

The X file:

trap "echo $[++i]" 0; EXIT –> 0$((...)) -> $[...] ;-) bash builtins only - 26 bytes Straight forward while using only bash builtins. IOW: No external helpers. The X file: trap "echo$((++i))" exit;

(No final newline.)

Proof of the pudding:

$bash <(cat X) 1$ bash <(cat X X)
2
$bash <(cat X X X) 3 Concat with or without newline inbetween:$ cat X X ; echo # added echo compensates missing \n only
trap "echo $((++i))" exit;trap "echo$((++i))" exit;
$bash <(cat X X) 2$ cat X <(echo) X ; echo
trap "echo $((++i))" exit; trap "echo$((++i))" exit;
$bash <(cat X <(echo) X) 2 Implicit, 2 1 byte -1 thanks to ASCII-only . :) • Link's broken for me – praosylen Mar 27 '18 at 4:17 • @AidanF.Pierce fixed. – MD XF Mar 27 '18 at 18:32 • . seems to work? – ASCII-only May 14 '18 at 10:35 Keg, 2 bytes This indeed works. (Works in the old TIO version, I don't know which version is this) 1+ A version that I can understand, 4 bytes 1(+) Explanation: 1# Push 1 onto the stack (+)# Add the whole stack together • This probably has something to do with why it works. I can't quite tell what the stack is doing, though, because TIO seems to be running an older and significantly different version of Keg.py where line 67 is return self.content.pop(). – Unrelated String Sep 13 '19 at 3:08 • @UnrelatedString, I haven't asked Dennis to update Keg on TIO yet because we're still testing to see that I haven't broken everything by implementing functions – lyxal Sep 13 '19 at 22:46 K (ngn/k), 3 bytes +/1 Try it online! +/1 - sum 1. returns 1 +/1+/1 - rightmost +/1 evaluates to 1 (as above), giving +/1 1, i.e. sum the vector 1 1. returns 2 GAS x64 Assembly (Linux, GCC 10.1): 143 107 104 100 bytes Assembled with -no-pie -nostdlib. Original code lea a,%rsi lea 2,%dx lea 1,%di lea 1,%ax syscall .ifndef b ja b .endif a=. .ascii " 1\b2" a=a+2 b=.; Annotated Single Single one segfaults, printing 1 to the terminal with a leading space. (Rules say this is OK.) // Print 2 characters from a // Use lea so we don't need$.
// We are optimizing for assembly, not machine code
lea a,%rsi
lea 2,%dx
lea 1,%di
lea 1,%ax
syscall

// Since b hasn't been defined yet, this gets left in, jumping to b
// (Pseudo-op is needed when we double)
.ifndef b
// Since gcc clears all flags at the start
ja b
.endif

// You can define re-writable labels like this too!
a=.
.asciz " 1\b2"

// Increase a by 2 (needed in double version)
a=a+2

// Attempt to jump here, but crash because there's no executable code
// Also, intentional semicolon to separate double version
b=.;

// Let crash

Gives the following:

1[1]    74584 segmentation fault (core dumped)  ./a.out

The first 1 is the program output. Since Segfault stuff isn't program output, we're good.

Annotated Double (fluff removed)

Takes advantage of the backspace character, overwriting the 1 with a 2. (Also segfaults)

// Print 2 characters
lea a,%rsi
lea 2,%dx
lea 1,%di
lea 1,%ax
syscall

ja b

// Every reference to a prior to this line points here
a=.
.ascii " 1\b2"
// Now point a to \b for next usage
a=a+2

// Now print the last two characters from new a
b=.
lea a,%rsi
lea 2,%dx
lea 1,%di
lea 1,%ax
syscall

// Crash
2[1]    391605 segmentation fault (core dumped)  ./a.out
• Before trying to improve this: Don't get confused between ASCII '1' and byte 0x1. This is very easy to do when you're dealing with low-level. ASCII '1' is 0x31 or 49, which none of these instructions or operands will assemble to in bytecode. – Calculuswhiz Jun 7 '20 at 2:30

Flurry, 6 bytes

([])[]

Verification

$echo -n "([])[]" | wc -c 6$ ./flurry -nin -c "([])[]"
1
$./flurry -nin -c "([])[]([])[]" 2 Found by accident (kind of). Single copy returns 1, two copies returns 2. (...) pushes its content to the stack, and [] evaluates to the stack height in Church numeral. Juxtaposition is function application (which is reversed exponentiation for Church numerals), so the entire code evaluates like the following: Single copy ([]) Evaluate to stack height (0), and push 0 to the stack [] Evaluate to stack height (1) Function application gives 1 ** 0 = 1 Two copies ([])[] Evaluate as above; evaluates to 1 and pushes a 0 ([]) Evaluate to stack height (1), and push 1 to the stack Function application gives 1 ** 1 = 1 [] Evaluate to stack height (2) Function application gives 2 ** 1 = 2 Honorable mention goes to the literal 2: Flurry, 10 bytes {<({}){}>} Returns 2 as-is, and returns 4 (= 2**2) when doubled. I call it a "literal" because it is a single pure {...} node (so it can be placed in larger programs without modification), and any number constant can be constructed using the same pattern. { Start a lambda; implicitly pushes its argument before running < Start a function composition group ({}) Pop the argument {} and push again (...) {} Pop the argument again > End composition group } End lambda Evaluates to the following lambda function \f. f ∘ f = \f. \x. f (f x) = 2 To create a higher number n, we can place n-1 copies of ({}) before {}, which then evaluates to \f. f ∘ f ∘ ... ∘ f (n copies), which is precisely n in Church numeral. For example, 3 can be written as {<({})({}){}>}, which is similar to what I previously used. Add++, 11 bytes o +1 o:"" o Try it online! The variable o isn't used, so the program is essentially equal to: o +1 o All you need to know is that o outputs the active variable, which starts at 0, and that +1 increments the active variable. This program is equivalent to this one. Doubled o +1 o:"" oo +1 o:"" o Try it online! o is an empty string, so we can disregard the oo. The o variable isn't used anywhere else, so we can ignore those, and we get this program: o +1 +1 o This program is equivalent to this one. x86 Linux machine code, 16 15 bytes XX is a linker placeholder for 15 bytes past the first instruction. It can still be repeated. Place it in its own write+execute section. 00000034: 04 04 b9 XX XX XX XX 80 01 34 43 42 cd 80 cc .........4CB... // We modify bytes "in" this section .section ".wtext","awx",%progbits .intel_syntax noprefix .globl _start _start: // Assumes the default Linux startup state, // where all regs except ESP are zero. // EAX = 4 // This is encoded as 04 04, which is important. add al, 4 // Set ECX to point to....nothing? mov ecx, offset 1f // Add '4' into.... nothing? add byte ptr [ecx], '4' // EBX = 1 inc ebx // EDX = 1 inc edx // write(1, 2f, 1) int 0x80 // Exit by raising a SIGTRAP (#BP). // We must exit: if we double the program, it will run twice. int3 1: // Nothing This abuses the Linux program startup state where all registers are zero, and how it doesn't get mad if you read or write a few bytes past the end of a section. Specifically, Linux will zero pad the section to a page boundary. It doesn't care about it until you go too far out of bounds. So label 2 when we only have one copy is this: 2: .byte 0x00 But when we double the code, we have this: 2: add al, 4 Let's expand the encoding: 2: .byte 0x04, 0x04 So, when we have one copy, it is 0, and when we double it, we get 4. So all we have to do is add ASCII 4 to get '4' on a single and '8' on double. Try it online! (Single) Try it online! (Double) vJASS (Warcraft 3), 150 bytes //! inject main set bj_randDistCount=bj_randDistCount+1 call ClearTextMessages() call BJDebugMsg(I2S(bj_randDistCount)) //! dovjassinit //! endinject prints 1 //! inject main set bj_randDistCount=bj_randDistCount+1 call ClearTextMessages() call BJDebugMsg(I2S(bj_randDistCount)) //! dovjassinit //! endinject //! inject main set bj_randDistCount=bj_randDistCount+1 call ClearTextMessages() call BJDebugMsg(I2S(bj_randDistCount)) //! dovjassinit //! endinject prints 2 Explanation: • bj_randDistCount is a non-constant integer variable. Also, it has the shortest variable name you may find in blizzard.j. • ClearTextMessages() clears all text messages in your in-game screen. • I2S(int whichInt) -> string converts from integer to string • BJDebugMsg(string str) prints text on your in-game screen. ><>, 24 20 bytes \0r+n; " " 0 8 p 1 Try it online! Uses the same trickery as my original 24 byte answer, just outputs 1 and 2 instead of 2/4. \0r+n; " " 0 a p 1 1 + Try it online! And try the double! This starts at the \, diverts code execution down, does its trick*, pushes two 1's, then wraps around again. It hits the \ again, but from a different angle now, so the 0r+n gets executed and ; terminates the program. (*) Note that the trick is to alter the source code by turning the instruction at 0, 10 into a space instead of a \ when the code is doubled. When the code hits n; (print number and quit), the top of the stack is either 2 or 2, 2. In each case, a 2 gets printed, So we need to add 2 and 2 in case of the double source code, but we don't have a second stack item on the regular run. This is solved by 0r: push a zero and reverse stack. We now either sum 2 and 2 and ignore the (now bottom) 0, or we add 2 and 0. Carrot, 4 bytes 2^F* Outputs 2 normally and 4 when doubled. Explanation normal: 2 //Input on the stack ^ //Convert to operations mode F //Convert stack to float mode * //Multiply stack by an empty argument (don't do anything) //Implicit output of stack Explanation doubled: 2 //Input on the stack ^ //Convert to operations mode F //Convert stack to float mode *2 //Multiply stack by 2 ^ //Convert to string stack mode F* //Place the literal "F*" onto the string stack //Implicit output of float stack In Carrot there are three stack modes: string, float and array. Only the current stack modes stack is output at the end of the program. PowerShell, 47 bytes (gc$MyInvocation.MyCommand.Definition).Length#

Try it online! (Output: 47)

Output:

47

Explanation

(gc $MyInvocation.MyCommand.Definition).Length# ^ ^ ^ ^ ^ ^^ | | | | | || | | | | | |No newline and/or whitespace at the end | | | | | | | | | | | Hash - Marks all next text as comment | | | | | | | | | Length - Returns length of string | | | | | | | Definition - Returns full path to script file | | | | | MyCommand - Contains information about the script file | | |$MyInvocation - Auto variable containing information about the current script
|
Alias for Get-Content commandlet, returns content of file

TI-Basic, 4 bytes

Fairly simple. I'm wondering if there are many alternate solutions.

1:2Ans       --> prints 2
1:2Ans1:2Ans --> prints 4

Alternate solutions

1+0 <-- 3 bytes based on @alexanderbird's answer
• what's wrong with (2 ? – Oki Sep 10 '17 at 18:36
• @Oki Nothing? I just didn't consider that. Mind if I change my answer to add that one? – Timtech Sep 11 '17 at 16:32
• i don't mind. tough your solution is much fancier – Oki Sep 12 '17 at 11:27

Java, 121 bytes

Original Code:

class A {static int n=1;public static void main(String[]a){System.out.print(n);}}/*
class B extends A{static{n++;}}//*///

Duplicated Code:

class A {static int n=1;public static void main(String[]a){System.out.print(n);}}/*
class B extends A{static{n++;}}//*///class A {static int n=1;public static  void main(String[]a){System.out.print(n);}}/*
class B extends A{static{n++;}}//*///

Technically you have to run the main method of A the first time, and of B the second time. Still, it's one program.

• You can save a byte when you remove the whitespace class A { – Edwardth Jul 19 '17 at 14:51

Common Lisp REPL, 25 bytes

(if(boundp'z)6(setq z 3))

Try it online!

Try the double version online!

• The rule says "to be full program"... wait that's REPL. – tail spark rabbit ear May 4 at 6:38

Klein, 5 + 3 = 8 bytes

\+@
2

The single program puts a two on the stack and attempts to add it. There is nothing to add so it is a noop and outputs 2. In the doubled program the \+@ section is not encountered but we do hit an additional 2 meaning that when we add again we add two 2s instead of a 2 and a zero. This results in 4. 2 can be replaced with any single digit number and this will still work, + can also be replaced with a * as long as we keep the 2, and \ can be replaced with a /.

PHP, 4847 43 bytes

<?php ob_end_clean();ob_start();echo++$i;?> Try it online! Result: 1 There's 2 PHP answers on here already, one of them looks like a port from Python and the other one breaks the error rule imo, so there's my shot at it. Doubled: PHP, 9695 86 bytes <?php ob_end_clean();ob_start();echo++$i;?><?php ob_end_clean();ob_start();echo++$i;?> Try it online! Result: 2 Explanation: ob_end_clean() once called, turns off the ob_start(). However, ob_end_clean will only clean items that started within the ob_start(). So to counter act this, we clear it first, run ob_start() then execute our counter. • Welcome to PPCG! I believe you can remove some newlines (after the semicolons) to save some bytes. – Stephen Aug 8 '17 at 13:14 • Good spot, thank you :) And thanks for the welcoming! – IsThisJavascript Aug 8 '17 at 13:23 k, 2 bytes *2 Try it online! A "monadic" (one argument) * means "first", and a dyadic (two argument) * is multiplication. Therefore *2 is seen as "the first element of a list containing 2", which is 2. *2*2 first evaluates 2*2, which is 4, and then evaluates *4, which is 4. Perl, 15 bytes ++$_,exit print

Try it online!

Doubled:

++$_,exit print++$_,exit print

Try it online!

Increments $_ to 1 in the first instance, print outputs$_ by default, and we pass that as an argument to exit. When doubled, print explicitly outputs ++$_ which is now 2. Carrot, 5 bytes ^F+1 Explanation: ^ --- Stack mode F --- Convert to float +1 --- Add 1 to the previous result <space> -- I have no idea Brian & Chuck, 15 bytes >>.>?2<<<?1 !>. >>.>?2<<<?1 !>.>>.>?2<<<?1 !>. Try it twice! This was my first attempt at learning Brian & Chuck. I took a short break after writing this answer and I've forgotten most of how it works. It relies on the facts that: • Chuck's 4th value is zero in the single program and non-zero in the double • . is a no-op in Brian's instructions, but prints in Chuck's instructions • In the double program, Brian's instructions are appended to Chuck's, but Chuck's are ignored because they're on the 3rd line. Ly, 6 bytes 1&+s>l Try it online! breakdown Command Operation stack content cell 1 push 1 1 &+ push sum of the stack 1,1 s pop to backup cell 1 1 > next stack 1 l push backup cell 1 1 implicit output of stack - or second execution: 1 push 1 1,1 1 &+ push sum of the stack 1,1,2 1 s pop to backup cell 1,1 2 > next stack 2 l push backup cell 2 2 implicit output Cubix, 4 5 bytes Of course as soon as I look at it again this presents itself. Not as nice as the previous, but shorter. ))O@ Try it online! ) ) O @ . . Increment, output and exit. ))O@))O@ Try it online! ) ) O @ ) ) O @ . . . . . . . . . . . . . . . . Increment twice, output and exit TI-BASIC, 2 bytes 2! There are also 5 more solutions, of equal or greater length. (2 abs(2 int(2 iPart(2 round(2 These all work on the same principle. Something evaluates to 2, and twice it is merely 2*2. • You should consider changing your formatting to have your solution in a separate code block prior to your outputs for both the singlet and doublet forms – Taylor Scott Sep 10 '17 at 19:13 Bash + coreutils, 43 bytes x=$(history|cut -c 8-|tail -1);echo ${#x};# Explanation Outputs the length of the last command entered. Uses the same concept as the Python and PHP solutions to prevent execution of any further copies (finishes with a comment marker, so anything after it is ignored). Length of the command will be doubled when it is written twice, hence the output. • Can't you simplify this to echo${#0};#? – Neil Jul 15 '17 at 19:12
• i dont know about the above comment, but tail -n 1 can be shortened to tail -1 – phil294 Jul 15 '17 at 20:00
• @Neil I tried that but echo ${#0};# outputs 4 and echo${#0};#echo ${#0};# also outputs 4 – Darren H Jul 15 '17 at 20:44 • @Blauhirn nicely spotted, thank you – Darren H Jul 15 '17 at 20:44 • @Neil That would output the filename next to the count. You need to use a pipe like wc -c <$0 # – Richard Jul 17 '17 at 14:35

Julia 0.6, 41 bytes

My first two ideas were already done in python answers (check file length, use a finalizer on an object). So here I check if π is an integer to gate the code that sets π=1 and registers the print to occur on exit. Then just double π each time.

π%1>0?(π=1;atexit(()->show(π))):π*=2;

Try it online!

Try twice it online!

• π>3 instead of π%1>0 works too – MarcMush Mar 4 at 10:26
• as well as π=2 instead of π*=2 – MarcMush Mar 4 at 10:27

Julia 0.6, 24 bytes

Riffing off of lungj's Python 3 answer. This works on my terminal on my mac, but not on TIO. The \r should reset back to the start of the line, so it always overwrites the previous output. Uses string interpolation with $to execute π=2π÷1 which doubles π and uses integer division to round it to an integer. It does output "WARNING: imported binding for π overwritten in module Main" as well, but thats not an error, and is pretty close to a compiler warning. print("\r$(π=2π÷1)");

Try it online!