Sign up ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

The Challenge

Write a complete program that writes twice as many bytes to standard output as the length of the program.

Rules

  • The program must write ASCII characters to the standard output.

  • The contents of the output doesn't matter.

  • The output, measured in bytes (trailing newlines optional, and included in byte count) must be exactly twice the length of the program, also measured in bytes, unless you fulfill the bonus.

Bonus

Your program can optionally take a number, n, as input. If so, the output must be exactly n * program length bytes. You can assume that n will always be a positive integer. If no input is provided, n must default to 2.

Reward: -25 bytes

Restrictions

  • No file/disk/network io allowed.

  • No standard loopholes.

  • The program must be at least 1 byte long.

  • No adding unnecessary whitespace to the source code to change its length. Similarly, comments don't count.

  • Unless you fulfill the bonus, the program must accept no input. If you do fulfill the bonus, the integer must be the only input.

Lowest score (program length in bytes - bonus) wins.

The shortest answer for each language wins for that language.

Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

# Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

# Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

# Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the leaderboard snippet:

# [><>](http://esolangs.org/wiki/Fish), 121 bytes

var QUESTION_ID=59436,OVERRIDE_USER=41505;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\-?\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\-?\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>

share|improve this question
    
For the bonus, does the output have to be exactly n * program length bytes, or is that a minimum? –  xnor 2 days ago
1  
It has to be exact –  Daniel M. 2 days ago
    
Looks like the code snippet has to be modified to handle negative scores. –  El'endia Starman 2 days ago
7  
A bonus of -25 is basically mandatory for some languages, since it lets them achieve a negative score. In the future, I'd suggest using a percent bonus, or just making the bonus the question if you really want answers to go for it. Or, just don't have a bonus. –  xnor 2 days ago
1  
For "no input is provided", do we assume the empty string is passed in? I can't see how one would deal with the user never typing in an input and the program just waiting. –  xnor 2 days ago

68 Answers 68

HQ9+, 2 bytes

QQ

outputs

QQQQ

I think it is not forbidden here.

share|improve this answer
    
It may not be forbidden, but it's not very inter... wait, how did it get eight upvotes? –  Jan Dvorak yesterday
6  
@JanDvorak Much as I dislike HQ9+, this to me is a creative use. This usage most likely wasn't envisioned when HQ9+ was created, which is more than can be said of most other Hq9+ programs. +1 from me. –  Digital Trauma yesterday

Python 2.6, 10

print`-.1`

Prints -0.10000000000000001, which is 20 chars.

Note that the string repr shows more precision. print-.1 just gives -.1, and print.1/3 gives 0.0333333333333 for only 13 digits of accuracy.

share|improve this answer
    
This no longer works in Python 2.7 or 3.1. –  Anders Kaseorg 2 days ago

CJam, -17 bytes

r2e|i8,*

The source code is 8 bytes long and qualifies for the -25 bytes bonus.

Try it online.

How it works

r         Read a token from STDIN.
 2        Push 2.
  e|      Logical OR; keep the token if it's not empty, 2 otherwise.
    i     Cast to integer.
     8,   Push [0 1 2 3 4 5 6 7].
       *  Repeat it the corresponding number of times.
share|improve this answer
1  
Crap. Well done. –  The_Basset_Hound 2 days ago
    
How is it negative bytes? –  Nick T 6 hours ago
    
@NickT 8 bytes (source code) - 25 bytes (bonus). –  Dennis 6 hours ago

Mathematica, 1 byte

#

Prints #1.

share|improve this answer

Shakespeare, 768

Yeah, Shakespeare's not much of a golfing language. Outputs 1,536 spaces.

Rosencrantz and Guildenstern: A Series of Tedious Events.

Rosencrantz, a count of extraordinary determination.
Guildenstern, a spacy character.

Act I: The Long Conversation

Scene I: A Tortured Friendship

[Enter Rosencrantz and Guildenstern]

Rosencrantz:
 You are a gentle, noble, valiant, loyal, loving companion.

Guildenstern:
 You are nothing!

Scene II: Asking the Hard Questions

Rosencrantz:
 Speak your mind.

Guildenstern:
 You are as fair as the sum of yourself and a daisy. Are you as
 daring as the sum of a big, bold, fiery, feisty, rough, rowdy,
 ham-fisted, hawk-eyed, broad-shouldered, bright-eyed lad and a
 large, yellow, vicious, hairy, wild, scary, long-tailed,
 sharp-clawed, small-eared lion?

Rosencrantz:
 If not, let us return to scene II.
share|improve this answer
1  
I'll +1 if you actually golf this. –  Thomas Kwa yesterday

Recall, 17 bytes

................!

17 NOOPs. Then the debugger ! is invoked and dumps the memory to the console. The memory is empty, but the header is 34 bytes long:

-- STATE DUMP --
----------------

Try it here.

share|improve this answer

Matlab, 7 bytes

'a':'e'

Output:

enter image description here

The output contains newline ans = newline newline abcde newline, so 14 bytes.

share|improve this answer
    
Let's hope nobody has format compact as default :) –  sanchises 2 days ago
1  
@sanchises :-) Yes, that depends on how Matlab's preferences have been set. But format loose is the default preference –  Luis Mendo 2 days ago

Python 2, 11

print`id`*1

Print the string representation of the built-in id, which is 22 chars:

<built-in function id>

The *1 is to get the code to 11 chars. You could also do print id;00.

More boring alternative 11's are:

print'1'*22
print 9**21
share|improve this answer
    
I've been playing around with complex numbers, but unfortunately print.8/-9j is one char short –  Sp3000 yesterday

Pyth, -15 -16

-1 by Dennis

**N9?zvz2

Prints [input]*9 quote characters, or 2*9 if the input is empty.

isaacg has a shorter answer here

Pyth, 1 byte

T

Prints 10. It's a built in variable that initializes to 10.

share|improve this answer
    
It would be useful if .x worked with errors. Is there a justification for why it doesn't? –  Thomas Kwa 2 days ago
    
My best guess is that Q causes Pyth to eval the input before the actual code is executed. **N9.xvz2 works as expected, but it's not shorter than **N9?zvz2. –  Dennis yesterday
    
@Dennis Interesting, and thanks. I should have known empty strings were falsy. –  Thomas Kwa yesterday

gs2, -18 bytes

CP437: W↕0!↨.2

Hex dump: 57 12 30 21 17 2e 32

W reads numbers from STDIN into a list. ↕0 appends a 2 to the list, and ! extracts the first element. Then ↨. (the list [0,1,2,3,4,5,6]) is repeated (2) this many times.

This is very similar to Dennis's CJam answer -- gs2 just combines r and i into one byte.

Note: I had to fix a bug in the gs2 implementation for this to work: previously, each program had a hidden newline appended to its output, which was entirely unintentional. It only surfaced after I tried to solve this program (the language was designed for anarchy golf, which ignores trailing newlines in all problems), and I only pushed a fix to master just now, so feel free to take this answer with a grain of salt.

share|improve this answer

dc, 10 - 25 = -15

2?A*Ar^1-n

Takes a blank line for "no input".

Calculates 10 ^ (10 * n) - 1, where n is the input, or 2 if input is empty. Prints a string of 9s of the required length.

  • 2 push 2 to the stack in case input is empty
  • ? push input to the stack
  • A push 10 to the stack (dc has shortcuts A-F for 10 - 15)
  • * pop twice and multiply (multiply input by 10)
  • A push 10 to the stack
  • r reverse top two stack elements
  • ^ exponentiate 10 ^ (10 * input)
  • 1- subtract 1 from the top of stack
  • n print with no newline.
share|improve this answer
    
dang, that is so clever. And lucky with the code length there :) But maybe you should add a small explanation for the uninitiated. And I think newline counts, so you should probably use n instead of p. –  daniero 2 days ago
    
@daniero Explanation added. –  Digital Trauma yesterday

CJam, -9

q_,{i}{;2}?G*'X*

Explanation

  • q_,

Reads the entire input and pushes it, then pushes the length.

  • {i}{;2}?

If the length of the input is over zero, convert it to an integer. Otherwise, pop the input and push 2.

  • G*

Pushes 16 (the program length), then multiplies it by 2 if there is no input, or by the input.

  • 'X*

Pushes X and multiplies it by the top of the stack.

share|improve this answer
    
@ThomasKwa Whoops. Updating in a sec. –  The_Basset_Hound 2 days ago
    
The comma is not necessary, however you can avoid the "if" altogether if you do a logical "or": q2e|i will give you the number you want –  aditsu yesterday
    
Also you could use S instead of 'X, the only issue is that the output will not be visible until you select it (well, if you run it offline and redirect to a file, it's not a problem) –  aditsu yesterday
    
Uh.. nevermind, I just saw Dennis's answer now :p –  aditsu yesterday
    
Even with the conditional, you can shorten this. You don't need to calculate the length, since an empty string is already falsey. You also don't need to pop the empty string off the stack, since it does not contribute to the output. Which also allows yo to avoid the braces for the else branch. I came up with this before I looked at any of the answers: r_{i}2?SB**. –  Reto Koradi yesterday

C, 27

main(){printf("%0.36f",0);}

prints 0.000000000000000000000000000000000000 which is 38 bytes long.

share|improve this answer
1  
I do not think that counts as a valid C program but main(){printf("%0.XXf",0);} works. –  ryvnf 20 hours ago
    
But you have to #include <stdio.h>, right? –  Zereges 3 hours ago
1  
@Zereges No, C has the "implicit declaration" rule that usually lets you use stuff without the proper #include. The compiler will emit a warning, and it will sometimes crash, but it will usually work. –  anatolyg 3 hours ago
    
@ryvnf Thanks, good point! Got it in. :) –  Albert Renshaw 3 hours ago
    
@anatolyg Thanks for the reference :D –  Albert Renshaw 3 hours ago

dc, 19 - 25 = -6

2?19*[1n1-d0<l]dslx

Takes a number (2 is pushed to the stack as backup) and multiplies it by 19. Prints a 1 (no newline) and decrements the number. Loops while the number is greater than 0.

share|improve this answer

Macaroni 0.0.2, 23 chars

print tobase pow 32 9 2

Prints 329 in binary, which happens to conveniently turn out to be 46 characters long (it's 1000000000000000000000000000000000000000000000), without a trailing newline.

share|improve this answer

Perl, 27 bytes - 25 = 2

$n=pop||2;print"n"x($n*27);

Thanks to the excellent commentators for their help on this one :)

It produces 27 "n"'s multiplied by $n, which defaults to 2 if @ARGV is undefined.

share|improve this answer
    
I think this fails for empty input. Per the rules, if no input is provided, the multiple should default to 2. –  Alex A. 2 days ago
    
@AlexA. Damn, I missed that. New to code golf. Edit incoming, but my answer has a lot of characters now because I have no idea how to do this more creatively in perl :( –  Codefun64 2 days ago
1  
Hey there, a few more tips that might help you here, by default in a program script, pop and shift work on @ARGV (in a sub they work on @_) so you could do something like $n=pop||2 to get the first code block down, and you have ;} at the end, which can almost always be just } to save another. Something that might help you save more chars is the string repetition operator x, consider print 1x20 or something along those lines... :) Hope that helps! –  Dom Hastings 2 days ago
    
@DomHastings Man, thanks! I got it down to 2 bytes total because of your help :) Thank you very much for your suggestions. –  Codefun64 yesterday

TI-Basic, 3 bytes

1ᴇ5

Prints 100000.

share|improve this answer
    
Actually, I think the newline would count, so you can just do 0 for 1 byte. –  Thomas Kwa yesterday

Julia, 42 bytes - 25 = 17

print("@"^42((r=readline())>""?int(r):2))

This reads a line from STDIN using readline(). If it's empty, i.e. no input has been provided, then n is defined to be the input converted to an integer. Otherwise n is 2. We then print 42​n @s to STDOUT.

share|improve this answer

JavaScript ES6, 33 - 25 = 8

(a=2)=>Array(a*33).fill(0).join``
share|improve this answer

><>, 21 + 2 (-v flag) - 25 = -2 bytes

l0=?2f6+*v
-1o;?=0::<

test it here!

Thanks Cole for helping fix my errors

First checks the stack length, if it's 0 put 2 on the stack. Multiplies it by 21 (code length), then outputs the unicode representation of that number and decrements it by 1, loops until 0. (you'll have to inspect the output to see the characters, since the browser won't display them)

share|improve this answer
    
Yeah, sorry to ruin your answer (but it is shorter than mine, if that makes you feel better). Edit: whoops hit enter too soon, your entry as it stands right now is not valid per the rule "You can assume that n will always be a positive integer. If no input is provided, n must default to 2." I also think it might print one too many characters (It goes from 14 to 0 which is 15 characters by my count, not 14). If I'm correct, l0=?2f6+*v as the first line and 1-::0=?;o> as the second should make it right. –  Cole 2 days ago
    
Hm, not sure what you mean. It shouldn't print 0 in any case. Putting a 2 as the initial stack outputs (EDIT: stuff i can't paste) which, at least using this char counter, is 28 chars. –  torcado 2 days ago
    
I understand what you're saying now. I interpreted "Your program can optionally take a number, n, as input" meaning that if the input would be 2. I'll edit the answer, thanks! (also i can save some by using a string instead of numbers) –  torcado 2 days ago
    
Happy to help, especially if it's ><>. –  Cole 2 days ago
    
?! is usually better than 0=? –  Sp3000 yesterday

q, 10 3 bytes

3#0

Outputs 6 bytes: "0 0 0\n".

share|improve this answer
1  
If I understand the challenge correctly, an 8-byte long program should produce 16 bytes of output... –  undergroundmonorail 2 days ago
    
Right. I should have read past the title. I've updated my answer. –  Alexander Belopolsky 2 days ago

Perl, 18 - 25 = -7

print$=x(<>*9||18)

The special variable $=, a.k.a. $FORMAT_LINES_PER_PAGE, begins its life as 60, and therefore only needs to be duplicated half as many times as byte output needed.

share|improve this answer
1  
I had a very similar answer of: print$=x9x(pop||2) nice! –  Dom Hastings 2 days ago

JavaScript (ES6), 23 bytes - 25 = -2

(n=2)=>'x'.repeat(23*n)

Just for fun here's a quine version with a score of 27 bytes -25 =2

a=(n=2)=>`a=${a}`.repeat(n)
share|improve this answer
1  
Does this really write to standard output? –  immibis 2 days ago
    
It's a function return, using fat arrow notation. –  SpeedyNinja 2 days ago
2  
The spec requires a full program... –  Jan Dvorak yesterday
1  
Running this program just gives me a function. Its output is a function that the length isn't double, nor does it take standard input. –  Unihedron 22 hours ago

JavaScript, 4 bytes

~$ cat main.js
+1/0
~$ nodejs main.js
Infinity

I think this is the shortest possible JS solution without ES6 :P

share|improve this answer
    
What version of NodeJS do you have? This doesn't work with mine. –  Dennis 21 hours ago
    
This also works on Firefox console. –  n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ 3 hours ago

Ruby, 24 - 25 = -1

$><<?x*24*(gets||2).to_i
share|improve this answer

JavaScript (ES6), 50-25=25

a=prompt();alert("0".repeat(48*(isNaN(a|0)?2:+a)))
share|improve this answer

Bubblegum, 1 byte

Ä

prints

!#
share|improve this answer
    
That's two or three bytes, one character (depends on encoding). Do bytes == characters here? –  Nateowami 56 mins ago

JavaScript (ES6), 24 30 - 25 = 5 bytes

alert('s'.repeat(30*prompt()))
share|improve this answer
    
The question requires a full program. Your code will only work inside a REPL environment. –  Dennis 21 hours ago
    
@Dennis, there is no other way for JavaScript to receive input, and using prompt is standard practice in other golfing challenges where input is required. –  Patrick Roberts 21 hours ago
    
@PatrickRoberts If you use prompt to input, then you should use something like alert to output. –  Doorknob 20 hours ago
    
prompt isn't the issue. This will produce no output outside a REPL environment. –  Dennis 20 hours ago
    
I updated the answer to alert the value, also removing the unnecessary unary plus operator since the multiplication will coerce the value to a number. –  Patrick Roberts 18 hours ago

JavaScript (ES5), 68 bytes - 25 bonus = 43

alert(Array(1+(+prompt()||2)).join(document.scripts[0].textContent))

This script only works in a browser following at least DOM3 (with Node.textContent) and ECMAScript 5 (or perhaps an older version). I tried to make is as standard conforming and compatible as possible. It also assumes that the script is in the first script element of the document.

It actually concatenates multiple copies of the script itself, which is pretty awesome. Note that the snippet tool on SE puts extra whitespace around the script. We could ignore that whitespace with .trim() but I don't find it necessary considering the program is perfect without SE's meddling. Just save this HTML5 file if you want to see it run perfectly.

<!DOCTYPE html>
<html>
  <head>
    <title>Minimalist HTML5 page</title>
    <script>alert(Array(1+(+prompt()||2)).join(document.scripts[0].textContent))</script>
  </head>
</html>

This script uses prompt and alert because console.log is not part of any standard, even if most modern browsers use it. If the number of repetitions passed is not a valid number or is empty, it defaults to 2. If the input is a decimal number, the program crashes due the the invalid array length.

The code uses a few interesting features of JavaScript:

  • Array(1+(+prompt()||2))

    • Array(INT) creates an Array of INT cells.

    • +prompt() takes an input and turns it into a number. If we passed the input as a string, the Array function would simply wrap it in a one-element array.

    • +prompt()||2 returns the input if it is truthy, else it returns 2.

    • This whole code creates an array of N empty elements, where N is one more than the amount of repetitions asked.

  • .join(document.scripts[0].textContent)

    • The array's join(STRING) method creates a string by concatenating all the cells, putting the provided STRING between values. In this program, there are N+1 empty elements in the array, or exactly N in-between spots. The result will be a string containing N times the provided STRING.

    • document.scripts[o] is the first <script> element of the document.

    • The textContent of Node instances returns the whole text found inside them and their child nodes, including scripts.

share|improve this answer
    
Note that if you use ES6's str.repeat and still output the code itself, it brings the score down to 26, but it's a bit too boring :P –  Jacque Goupil 9 hours ago
    
Erm, I don't know where that 26 came from, now I get 33. I should probably get some sleep. –  Jacque Goupil 7 hours ago

Ruby, 6 bytes

p ?a*9

Prints "aaaaaaaaa" (including the quotes) and a newline.

share|improve this answer

protected by Community 19 hours ago

Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.