text:
Capture The Flag
This is a game of capture the flag, heavily inspired and based off of Red vs. Blue - Pixel Team Battlebots. That was an awesome question (thank you very much Calvin'sHobbies; I hope you don't mind that I shamelessly stole a lot of code from you) -- here's another team based king-of-the-hill. Hopefully, capture the flag will require more team cooperation as well as more strategy.
To mix it up, you are considered on the red team if the last digit of your id is between 0 and 4 inclusive. This should prevent the exact same teams from battling again, if the same people decide to answer. The board is 350px by 350px. The blue team starts on the upper half of the board and the red team starts on the lower half.
The way you play capture the flag is as follows: the object of the game is to take the opposing team's flag and bring it back to your own side. If you are on their side, you can be tagged and sent to jail. If you are in jail, then you can't move. If you are on your side, your job is to tag opposing team members to send them to jail. The only way to get out of jail is for someone on your team who is free to tag everyone in jail. (Note that jail is located on the opposing team's side).
Specifically:

There is a constant - FIELD_PADDING - set to 20. This is the padding for the field. If it were zero, then the flags and jail would be exactly on the corners of the canvas. Since it is not, the flag and jail are 20 pixels away from the corners.
The blue flag (remember: blue team is on the upper half) is located at (WIDTH - FIELD_PADDING, FIELD_PADDING) = (330, 20) i.e. top-right corner.
The red flag is at (FIELD_PADDING, HEIGHT - FIELD_PADDING) = (20, 330)
The blue jail (where red members are kept) is at (20, 20) i.e. blue side, top left.
The red jail, where blue members are kept, is at (330, 330)

Every team member starts randomly at a position 45 < x < 305 and 45 < y < 175 for blue and 175 < y < 305 for red. No team member can go within DEFENSE_RADIUS = 25 pixels of their own flag or their own jail (unless, of course, your own flag was taken by an opposing bot, in which case you need to tag that bot). This is to prevent puppy-guarding like bots. If you go within that range, you are "pushed" back. Similarly, no team member can go out of bounds (less than zero or more than 350) -- if you do, you are pushed back to the nearest legal place you can be.
Every time you move, you use up strength. Your strength starts out at 20 and is replenished by 2 every turn. The amount of strength you use is equal to the distance you travel. If your strength would become negative by moving to a certain place, you are prevented from making that move. It's probably a good idea to just go at speed 2 for normal chasing. You should only use higher speeds if you are close to winning and need the extra speed (in my opinion).
Spec:
The spec is quite similar to the Pixel Team Battlebots question. You should write a code block (remember, no global variables) in javascript. It should return an object with an x-value and y-value representing your change in x and change in y values. The following answer:
return {
  x: 0,
  y: -2
};

always moves up, until it hits a wall. You may not edit 8 hours after posting (except for LegionMammal98 who thought that the controller wasn't loading his/her code and didn't test). You have access to the following variables in your code:

this -- yourself, as a player (see below for what players are)
move -- the round number, starting at 0
tJailed -- an array of all players on your team that are jailed
eJailed -- an array of all players on the opposing team that are jailed
team -- an array of all players on your team, NOT just the ones near you
enemies -- an array of all players on the other team, NOT just the ones near you
tFlag -- your flag (you're trying to protect it)
eFlag -- the other flag (you're trying to steal it)
messages -- explained below
A list of constants: WIDTH = 350, HEIGHT = 350, FIELD_PADDING = 20, DEFENSE_RADIUS = 25.

Every "player" is an object with the following properties:

x and y
strength
id
isJailed -- true if the player is in jail

Every flag has the following properties:

x and y
pickedUpBy -- the player who currently has the flag, or null if no player has the flag.

Now, messages is an object that is shared among your teammates. I don't care what you do with it. The same object is shared and passed to every one of your team members. This is the only way you can communicate. You can attach properties to it, share objects, etc. It can be as big as you want -- no size limit.
Every turn the following happens:

The list of players (both red and blue) is randomly shuffled for turn order.
Every player makes a move.
If any red team members touch (within 10 pixels of) any blue team members on red's side, send the blue team members to jail, and vice versa. A jailed player drops his/her flag and has strength drop to zero. Note that the step function (code you provide) is still called -- so you can get/set messages, but you can't move while in jail.
If any player is touching (within 10 pixels of) the other flag, then the other flag is marked as "picked up by" that player. When the player moves, the flag moves -- until the player is tagged and goes to jail, that is.
If any player is touching the other side's jail, free everyone in that jail. When a player is freed from jail, he/she is teleported to a random location on his/her side.

Hints:

At least in regular capture the flag, attacks work much better when many players go at once, because it tends to confuse defenders as to which player they should chase.
Similarly, defenders might want to coordinate who they are chasing so that attacks don't go through

Stack snippet:

window.onload=function(){(function(){function p(a,b,c,e){return Math.sqrt((a-c)*(a-c)+(b-e)*(b-e))}function l(a,b){this.x=this.y=0;this.id=a.id;this.title=a.title+" ["+this.id+"]";this.link=a.link||"javascript:;";this.team=b;this.isJailed=!1;this.flag=null;this.moveFn=new Function("move","tJailed","eJailed","team","enemies","tFlag","eFlag","messages","WIDTH","HEIGHT","FIELD_PADDING","DEFENSE_RADIUS",a.code);this.init()}function x(a,b){return Math.floor(Math.random()*(b-a))+a}function q(a,b){this.startX=this.x=a;this.startY=
this.y=b;this.following=null}function t(a,b){return a===e&&b||a===h&&!b?{x:20,y:20}:{x:g.width-20,y:g.height-20}}function y(){var a,b=$("#redTeam"),c=$("#blueTeam");for(a=0;a<e.length;++a)e[a].addToDiv(b);for(a=0;a<h.length;++a)h[a].addToDiv(c)}function z(){d.clearRect(0,0,g.width,g.height);d.beginPath();d.moveTo(0,g.height/2);d.lineTo(g.width,g.height/2);d.stroke();var a=e.concat(h),b,c;for(b=a.length-1;0<b;b--){c=Math.floor(Math.random()*(b+1));var f=a[b];a[b]=a[c];a[c]=f}for(b=0;b<a.length;++b)a[b].step(u);
for(b=0;b<e.length;++b)for(c=0;c<h.length;++c)10>p(e[b].x,e[b].y,h[c].x,h[c].y)&&(e[b].y<g.height/2&&e[b].goToJail(),h[c].y>g.height/2&&h[c].goToJail());for(b=0;bp(a[b].x,a[b].y,c.x,c.y)&&(c.following=a[b]);for(b=0;bp(a[b].x,a[b].y,c.x,c.y))for(c=a[b].team,f=0;f<c.length;++f)c[f].isJailed&&(c[f].isJailed=!1,c[f].init());m.follow();n.follow();b=m.y<g.height/2;c=n.y>g.height/2;b&&c&&alert("EXACT TIE!!!! This is very unlikely to happen.");
b&&!c&&(alert("Blue wins!"),$("#playpause").click().hide());c&&!b&&(alert("Red wins!"),$("#playpause").click().hide());for(b=0;b<a.length;++b)a[b].draw(d);m.draw("red");n.draw("blue");u++}$.ajaxSetup({cache:!1});var e=[],h=[],g=$("canvas")[0],d=g.getContext("2d"),v,u=0,m={},n={},r=!0,A={},B={},w;l.prototype.init=function(){this.x=x(45,g.width-45);this.y=x(45,g.height/2);this.team===e&&(this.y+=g.height/2);this.strength=20};l.prototype.makeShallowCopy=function(){return{x:this.x,y:this.y,strength:this.strength,
id:this.id,isJailed:this.isJailed}};l.prototype.goToJail=function(){this.isJailed=!0;var a=this.team===e!==!0?m:n;(this.team===e!==!0?m:n).following===this&&(a.following=null);a=t(this.team,!0);this.x=a.x;this.y=a.y;this.strength=0};l.prototype.step=function(a){function b(a,b,c){var e,d,f;for(e=0;e<a.length;++e)d=a[e],d!==C&&(f=d.makeShallowCopy(),d.isJailed?b.push(f):c.push(f))}var c=[],f=[],d=[],k=[],l=this.team===e?h:e,C=this,q=this.team===e?m:n,r=this.team===e?n:m;b(this.team,c,d);b(l,f,k);f=
this.moveFn.call(this.makeShallowCopy(),a,c,f,d,k,q.copy(),r.copy(),this.team===e?A:B,g.width,g.height,20,25);"object"===typeof f&&"number"===typeof f.x&&"number"===typeof f.y&&(d=p(0,0,f.x,f.y),a=t(this.team,!1),c=this.team===e!==!1?m:n,d<=this.strength&&(this.strength-=d,this.x+=f.x,this.y+=f.y,0>this.x&&(this.x=0),0>this.y&&(this.y=0),this.x>g.width&&(this.x=g.width),this.y>g.height&&(this.y=g.height),f=p(this.x,this.y,c.x,c.y),d=p(this.x,this.y,a.x,a.y),25>f&&null===c.following&&(this.x=25*(this.x-
c.x)/f*1.3+c.x,this.y=25*(this.y-c.y)/f*1.3+c.y),25>d&&(this.x=25*(this.x-a.x)/d*1.3+a.x,this.y=25*(this.y-a.y)/d*1.3+a.y)),this.isJailed||(this.strength+=2),20<this.strength&&(this.strength=20))};l.prototype.addToDiv=function(a){var b=$("<option>").text(this.title).val(this.id);a.find(".playersContainer").append(b)};l.prototype.draw=function(a){a.fillStyle=this.team===e?"red":"blue";a.beginPath();a.arc(this.x,this.y,5,0,2*Math.PI,!0);a.fill();!this.isJailed&&$("#labels").is(":checked")&&a.fillText(this.title,
this.x+5,this.y+10)};q.prototype.draw=function(a){d.strokeStyle=a;d.beginPath();d.arc(this.x,this.y,5,0,2*Math.PI,!0);d.stroke();d.fillStyle=a;d.strokeRect(this.x-2,this.y-2,4,2);d.beginPath();d.moveTo(this.x-2,this.y);d.lineTo(this.x-2,this.y+3);d.stroke()};q.prototype.copy=function(){return{x:this.x,y:this.y,pickedUpBy:this.following&&this.following.makeShallowCopy()}};q.prototype.follow=function(){null!==this.following&&(this.x=this.following.x,this.y=this.following.y)};$("#newgame").click(function(){function a(a,
b){w?b(w):$.get("https://api.stackexchange.com/2.2/questions/"+(49028).toString()+"/answers",{page:a.toString(),pagesize:100,order:"asc",sort:"creation",site:"codegolf",filter:"!JDuPcYJfXobC6I9Y-*EgYWAe3jP_HxmEee"},b,"json")}function b(g){w=g;g.items.forEach(function(a){function b(a){return $("<textarea>").html(a).text()}var d=4>=a.owner.user_id%10?e:h;a.owner.display_name=b(a.owner.display_name);if(!(a.hasOwnProperty("last_edit_date")&&28800<a.last_edit_date-a.creation_date&&33208!==a.owner.user_id||
-1
=g.length)){var f={};f.id=a.owner.user_id;f.title=a.owner.display_name;f.code=b(g[1]);f.link=a.link;d.push(new l(f,d))}}});g.has_more?a(++d,b):(console.log("Red team",e),console.log("Blue team",h),y(),clearInterval(v),r=!0,$("#playpause").show().click())}var c=/
((?:\n|.)*?)\n<\/code><\/pre>/,d=1,p=[];e=[];h=[];u=0;m=new q(20,g.height-20);n=new q(g.width-20,20);$(".teamColumn select").empty();var k=
$("#testbotCode").val();0<k.length&&(console.log("Using test entry"),k={title:"TEST ENTRY",link:"javascript:;",code:k},$("#testbotIsRed").is(":checked")&&(k.id=-1,e.push(new l(k,e)),k.id=-3,e.push(new l(k,e))),$("#testbotIsBlue").is(":checked")&&(k.id=-2,h.push(new l(k,h)),k.id=-4,h.push(new l(k,h))));a(1,b)});$("#playpause").hide().click(function(){r?(v=setInterval(z,25),$(this).text("Pause")):(clearInterval(v),$(this).text("Play"));r=!r})})();}
#main{padding:10px;text-align:center}#testbot{padding:10px;clear:both}.teamColumn{width:25%;padding:0 10px;border:3px solid;border-color:#000;text-align:center;height:500px;overflow:scroll;white-space:nowrap}.playersContainer p{padding:0;margin:0}#redTeam{float:left;border-color:red;color:red;background-color:#fee}#blueTeam{float:right;border-color:#00f;color:#00f;background-color:#fee}#arena{display:inline-block;width:40%;text-align:center}canvas{border:1px solid #000}select{width:100%}

Red Team
<select size=20 class=playersContainer></select>

Battlefield
<canvas width=350 height=350></canvas>

Blue Team
<select size=20 class=playersContainer></select>

<button id=newgame>New Game</button> <button id=playpause>Play</button>
<input type=checkbox id="labels"> Show labels

<textarea id=testbotCode placeholder="testbot code"></textarea>
<input type=checkbox id="testbotIsRed">Red Team
<input type=checkbox id="testbotIsBlue">Blue Team

Controller: http://jsfiddle.net/prankol57/4L7fdmkk/
Full screen controller: http://jsfiddle.net/prankol57/4L7fdmkk/embedded/result/
Let me know if there are any bugs in the controller.
Note: If you go to the controller and think that it isn't loading anything, press "New Game." It only loads everything after you press "New Game" so that it can load all the bots and possible test bots at once.
Good luck.

If anyone wants to see an example game, I made an example bot that you can copy and paste into the "testbot" textarea (the testbot creates two duplicates on each team; check both red team and blue team):
var r2 = Math.sqrt(2);
if (this.id === -1) {
  // red team 1
  // go after flag regardless of what is going on
  if (eFlag.pickedUpBy !== null && eFlag.pickedUpBy.id === this.id) {
    return {
      x: 0,
      y: 2
    };
  }
  return {
    x: this.x < eFlag.x ? r2 : -r2,
    y: this.y < eFlag.y ? r2 : -r2
  };
}
if (this.id === -2) {
  // blue team 1
  // a) go after opposing team members on your side b) get the other flag if no enemies on your side
  var closestEnemy = null;
  for (var i = 0; i < enemies.length; ++i) {
    if (enemies[i].y < HEIGHT/2 && (closestEnemy === null || enemies[i].y < closestEnemy.y)) {
      closestEnemy = enemies[i];
    }
  }
  if (closestEnemy !== null) {
    return {
      x: this.x < closestEnemy.x ? r2 : -r2,
      y: this.y < closestEnemy.y ? r2 : -r2
    };
  }
  if (eFlag.pickedUpBy !== null && eFlag.pickedUpBy.id === this.id) {
    return {
      x: 0,
      y: -2
    };
  }
  return {
    x: this.x < eFlag.x ? r2 : -r2,
    y: this.y < eFlag.y ? r2 : -r2
  };
}
if (this.id === -3) {
  // red team 2
  // a) defend the flag b) if at least half of enemies in jail and no enemies on this side, free jailed reds and quickly return
  var closestEnemy = null;
  for (var i = 0; i < enemies.length; ++i) {
    if (enemies[i].y > HEIGHT/2 && (closestEnemy === null || enemies[i].y > closestEnemy.y)) {
      closestEnemy = enemies[i];
    }
  }
  if (closestEnemy !== null) {
    return {
      x: this.x < closestEnemy.x ? r2 : -r2,
      y: this.y < closestEnemy.y ? r2 : -r2
    };
  }
  if (enemies.length / eJailed.length <= 1 && tJailed.length > 0) {
    return {
      x: this.x < FIELD_PADDING ? r2 : -r2,
      y: this.y < FIELD_PADDING ? r2 : -r2
    };
  }
  if (this.y < 350/2) return {x: 0, y: 2};
  return {
    x: this.x < tFlag.x ? r2 : -r2,
    y: this.y < tFlag.y ? r2 : -r2
  };
}
if (this.id === -4) {
  // blue team 2
  // a) try freeing jail if there are jailed team members b) capture the flag
  if (tJailed.length > 0) {
    return {
      x: this.x < WIDTH - FIELD_PADDING ? r2 : -r2,
      y: this.y < HEIGHT - FIELD_PADDING ? r2 : -r2
    };
  }
  if (eFlag.pickedUpBy !== null && eFlag.pickedUpBy.id === this.id) {
    return {
      x: 0,
      y: -2
    };
  }
  return {
    x: this.x < eFlag.x ? r2 : -r2,
    y: this.y < eFlag.y ? r2 : -r2
  };
}

You may want to post this in meta as a sandbox post first (or even concurrently) like I did with RvB. It's a complicated type of contest, and having a place you and others can debug stuff is very helpful. (Btw, I don't mind you using my code, though I can't say it was documented or even organized terribly well :P)

I agree with Calvin that you should make a second copy of this post as a meta question.

It would be halpful if you changed the controller link to http://jsfiddle.net/prankol57/4L7fdmkk/embedded/result/ for fullscreen.

@Calvin'sHobbies Since I just copied the code from you, I'm pretty sure it will work (the ajax/obtaining answers stuff). I'm not so sure about the controller itself.

Isn't the controller one of the most important parts...?

You should mention how this provides your own information.

@AlexA Yeah, but how would posting it in the sandbox help fix bugs in the controller (not loading answers, running the answers)? People would have to start posting actual answers that work, which isn't, in my opinion, what meta is for, which means I should probably just post it here. Bugs will inevitably come up even in regular KOTH controllers.

Also, tJailed should include the player currently being called. Otherwise, you'd have to do several calculations to determine if you're in jail.

So, is this challenge ready to start? Can I post answers?

My bot isn't appearing on the controller.

@soktinpk We aren't talking about posting it in the sandbox, we're talking about posting is as a sandbox, a separate question which would allow you to test the controller.

@LegionMammal978 Yeah it is! It seems to be working. (Just press new game to load everything)

@PhiNotPi I know. But I'm using the exact same code as Calvin'sHobbies so why wouldn't it work? I thought opening a new question for already-tested code is sort of a waste...

@soktinpk But you aren't using my exact code. The answer loading and interface may be essentially the same (though at second glance, the interface really isn't) but the part that actually plays the game is different. People are more likely to spend time writing answers if they can see that some testing has been done and can trust that you will properly manage the contest. (I personally don't have these feelings of trust if only because the background of the blue team box is unaccountably pink.)

From running some games with the current submissions, it seems that a lot of games get into a stalemate situation.  How are those handled in the scoring?  Calvin's contest had a hard time limit, after which a tiebreaker condition was used.

You should make it so that when someone frees their teammates from jail, they also get teleported back to their side. This would prevent Lazy Jail Hogs.

This looks fun, but I wish it wasn't limited to JavaScript.

Blue - LegionMammal978
function repeat(el, n) // Helper function
{
    var rtn = [];
    for (var i = 0; i < n; i++)
        rtn.push(el);
    return rtn;
}
function sign(n) { return n ? n < 0 ? -1 : 1 : 0; } // Another helper function
if (!messages[this.id])
    messages[this.id] = { "dir": 1 };
if (this.isJailed) // Oh noes, I'm in jail!
{
    console.log(this.id, messages);
    if (!messages[this.id].jailTicks)
        messages[this.id].jailTicks = 0;
    messages[this.id].jailTicks++;
    // Call for help!
    messages.callsForHelp = repeat(["Help!", this.id, this.x, this.y], messages[this.id].jailTicks);
    return { "x": 0, "y": 0 };
}
if (messages[this.id].jailTicks)
    if (!(delete messages[this.id].jailTicks && delete messages.callsForHelp)) // Cleanliness
        messages[this.id].jailTicks = messages.callsForHelp = undefined;       // ...
var bounds = Math.floor(HEIGHT / 2); // Be safe with fractions
if (this.y > bounds - 5) // Get back to shelter!
    return { "x": 0, "y": this.y - this.strength <= bounds - 5 ? bounds - 5 - this.y : -4 };
var target = { "none": true, "x": WIDTH << 1, "y": HEIGHT << 1 };
enemies.forEach(function (en) { if (!en.isJailed && en.y < bounds - 5 && Math.abs(en.x - this.x) < Math.abs(target.x - this.x) && Math.abs(en.y - this.y) < Math.abs(target.y - this.y)) target = en; }, this);
if (target.none)
{
    if (this.y < bounds - 5)
        return { "x": 0, "y": 2 };
    var speed = this.strength < 30 ? 1 : 2;
    if (this.x == 5 || this.x == WIDTH - 5)
        messages[this.id].dir = -messages[this.id].dir;
    return { "x": speed * messages[this.id].dir, "y": 0 };
}
if (this.x - target.x >= 0 && this.x - target.x < this.strength)
{
    if (this.y - target.y > 0 && this.y - target.y < this.strength + target.x - this.x)
        return { "x": this.x - target.x, "y": this.y - target.y };
    if (target.y - this.y > 0 && target.y - this.y < this.strength + target.x - this.x)
        return { "x": this.x - target.x, "y": target.y - this.y };
}
if (target.x - this.x > 0 && target.x - this.x < this.strength)
{
    if (this.y - target.y > 0 && this.y - target.y < this.strength + this.x - target.x)
        return { "x": target.x - this.x, "y": this.y - target.y };
    if (target.y - this.y > 0 && target.y - this.y < this.strength + this.x - target.x)
        return { "x": target.x - this.x, "y": this.y - target.y };
}
return { "x": 6 * sign(target.x - this.x), "y": 6 * sign(target.y - this.y) };

Defense bot.

Little thing about javascript -- you can't use this inside of a function (in your forEach loop). You have to save it as a variable beforehand (i.e. var _this = this;) and use _this. I'll add you as an exception if you edit soon because you thought that the controller wasn't loading your code and couldn't test.

@soktinpk Just used forEach's optional thisArg.

I updated the controller to allow you even though you edited late.

Red - Lazy Jail Hog | Lazy Flagger
Moves towards the closer of these two: blue's jail, or blue's flag.

If going for the jail, will move into the jail and stop. (Since blue can't touch its own jail, it will be invincible and automatically free all allies)
If going for the flag, it will blindly move for the flag and return.

Finally, its brain is entirely stored in messages[29354] and initialized on the first move only. Thus, if allies find a better use for this bot, they can replace its brain for their higher purpose.
if (move === 0) {
    //On the first turn, set messages[this.id] to the function I will call to move me
    messages[this.id] = function(move, tJailed, eJailed, team, enemies, tFlag, eFlag, messages) {
        //Arbitrary function to move to a point at some speed, which may be in the point
        //  If we are at the point, undefined is returned
        var moveTo = function(p, max) {
            if (!p) {
                return {x:0, y:0};
            }
            max = Math.min(this.strength, max || p.max || 2);
            var dx = p.x - this.x;
            var dy = p.y - this.y;
            var dist = Math.abs(dx)+Math.abs(dy);
            if (dist === 0) {
                return undefined;
            } else if (dist < max) {
                return {x: dx, y: dy};
            }
            var ux = Math.floor(max * dx / dist);
            var uy = Math.floor(max * dy / dist);
            while (Math.abs(ux) + Math.abs(uy) < max) {
                if (ux + this.x !== p.x) {
                    ux += ux > 0 ? 1 : -1;
                } else if (uy + this.y !== p.y) {
                    uy += uy > 0 ? 1 : -1;
                } else {
                    break;
                }
            }
            return {x: ux, y:uy};
        }.bind(this);

        //Set the way points
        var points = [];
        if (this.x > WIDTH/2) {
            points.push({x: WIDTH-FIELD_PADDING, y:HEIGHT/2+5});
            points.push({x: WIDTH-FIELD_PADDING, y:FIELD_PADDING, max: 5});
            points.push({x: WIDTH-FIELD_PADDING, y:HEIGHT/2+25, max: 5});
        } else {
            points.push({x: FIELD_PADDING, y:HEIGHT/2+5});
            points.push({x: FIELD_PADDING, y:FIELD_PADDING, max: 5});
            points.push(undefined); //Special case to do nothing / hog the jail
        }

        //Move through the points
        var state = messages[this.id].state || 0;
        var ret;
        while (!ret) {
            //Special case: if we were doing nothing, make sure we're where we think we were
            if (!points[state]) {
                ret = moveTo(points[state-1]);
                if (ret) {
                    state = 0;
                }
            }

            //Move to the next point
            ret = moveTo(points[state]);
            if (!ret) {
                state = (state + 1) % points.length;
            }
        }
        messages[this.id].state = state;
        return ret;
    };
}
//Move me based on that function, which may be changed by my allies
return messages[this.id].call(this, move, tJailed, eJailed, team, enemies, tFlag, eFlag, messages);

The controller uses euclidean distance for movements.

Red - The Guard
This bot will guard the flag pretty good. Don't get in its way...
if (!messages[this.id]) {
    //On the first turn, set messages[this.id] to the function I will call to move me. You can replace this function on subsequent turns
    //to control it. Additionally, you can use it as a library to find one of the best places to go to defend.
    messages[this.id] = function(move, tJailed, eJailed, team, enemies, tFlag, eFlag, messages, WIDTH, HEIGHT, FIELD_PADDING, DEFENSE_RADIUS) {
        var distance = function(p1, p2) {
            var dx = p1.x - p2.x;
            var dy = p1.y - p2.y;
            return Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
        }

        var moveTo = function(p) {
            if (!p) {
                return {x:0, y:0};
            }
            var dx = p.x - this.x;
            var dy = p.y - this.y;
            var max = this.strength;
            var dist = distance(p, this);
            if (dist < max) {
                return {x: dx, y: dy};
            }
            dx = dx * max / dist;
            dy = dy * max / dist;
            while (Math.sqrt(Math.abs(dx)+Math.abs(dy)) > max) {
                if (dx > dy) {
                    dx = dx - 0.001;
                } else {
                    dy = dy - 0.001;
                }
            }
            return {x: dx, y:dy};
        }.bind(this);

        if (tFlag.pickedUp) {
            if (tFlag.y - HEIGHT / 2 > distance(this, {x: tFlag.x, y: HEIGHT / 2})) {
                return moveTo(tFlag);
            } else {
                return moveTo({y: Math.min(this.y, tFlag.y), x: tFlag.x });
            }
        }

        if (eFlag.pickedUp == this.id) {
            return moveTo({x: x, y: HEIGHT / 2});
        }

        var targetPoints = [];
        var crossedBorder = false;

        var weightedMiddlePoint = function(enemy) {
            var x1 = (enemy.x + tFlag.x) / 2;
            var y1 = (enemy.y + tFlag.y) / 2;
            var w = 1/Math.pow(distance(enemy, tFlag),2);
            return {x:x1,y:y1,w:w};
        }

        for (var i = 0; i < enemies.length; i++) {
            var enemy = enemies[i];
            if (enemy.isJailed){
                continue;
            }
            if (enemy.y > HEIGHT / 2) {
                crossedBorder = true;
            }
        }

        for (var i = 0; i < enemies.length; i++) {
            enemy = enemies[i];
            if (enemy.isJailed){
                continue;
            }
            if (crossedBorder) {
                if (enemy.y > HEIGHT / 2) {
                    targetPoints.push(weightedMiddlePoint(enemy));
                }
            } else {
                targetPoints.push(weightedMiddlePoint(enemy));
            }
        }

        if (targetPoints.length == 0) {
            return moveTo(eFlag);
        }

        var sumX = 0;
        var sumY = 0;
        var sumW = 0;

        for (var i = 0; i < targetPoints.length; i++) {
            point = targetPoints[i];
            sumX += point.x * point.w;
            sumY += point.y * point.w;
            sumW += point.w;
        }

        var targetPoint = {x: sumX / sumW, y: sumY / sumW};

        return moveTo(targetPoint);

    };
}

return messages[this.id].call(this, move, tJailed, eJailed, team, enemies, tFlag, eFlag, messages, WIDTH, HEIGHT, FIELD_PADDING, DEFENSE_RADIUS);

Red - Flag Hunter
var distance = function(x1, y1, x2, y2) {
    return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
}
var moveTo = function(x, y, max) {
    if (max > this.strength)
        max = this.strength;
    var dX = x - this.x;
    var dY = y - this.y;
    var dist = distance(x, y, this.x, this.y);
    if (dist <= max) {
        return {x: dX, y: dY};
    }
    dX = dX * max / dist;
    dY = dY * max / dist;
    while (Math.sqrt(Math.abs(dX)+Math.abs(dY)) > max) {
        if (dX > dY) {
            dX = dX - 0.001;
        } else {
            dY = dY - 0.001;
        }
    }
    return {x: dX, y:dY};
}.bind(this);

var getSurroundingPoints = function(x, y, dist) {
    var points = [];
    for (var i = x - dist; i <= x + dist; i+= 0.2) {
        for (var j = y - dist; j <= y + dist; j+= 0.2) {
            if (i >= 0 && j >= 0 && j <= 180 && distance(i,j,x,y) <= dist) {
                points.push({x: i, y: j, danger: 0});
            }
        }
    }
    return points;
}

if (this.isJailed) {
    return {x:0, y:0};
}

var destination = {x: eFlag.x, y: eFlag.y}; //default: try to get the flag
if (eFlag.pickedUpBy != null) { //we got the flag
    if (eFlag.pickedUpBy.id == this.id) { //I got the flag => get back to the red side
        if (distance(this.x, this.y, this.x, 175.1) <= this.strength) {
            return moveTo(this.x, 175.1, this.strength);
        }
        destination.x = this.x;
        destination.y = 180;
    } else { //someone else got the flag => free those in the jail
        destination.x = 20;
        destination.y = 20;
    }
} else if (this.y > HEIGHT / 2) { //I am on the red side
    return moveTo(175, 175, 2);
} else if (distance(this.x, this.y, eFlag.x, eFlag.y) <= 15)  { //I am in the safe zone (flag)
    if (this.strength < 20)
        return {x:0, y:0};
    return moveTo(eFlag.x, eFlag.y, 2); //get the flag
} else if (distance(this.x, this.y, eFlag.x, eFlag.y) - this.strength <= 15)  { //I can reach the safe zone (flag)
    return moveTo(eFlag.x, eFlag.y, distance(this.x, this.y, eFlag.x, eFlag.y) - 14);
} else if (distance(this.x, this.y, 20, 20) < 10)  { //I am in the safe zone (jail)
    if (this.strength < 20)
        return {x:0, y:0};
} else if (distance(this.x, this.y, eFlag.x, eFlag.y) - this.strength <= 15)  { //I can reach the safe zone (jail)
    return moveTo(20, 20, this.strength);
}

//I am somewhere on the blue side
var points = getSurroundingPoints(this.x, this.y, this.strength);
var me = this;
points.forEach(function(point) {
    if (point.y < 175) {
        enemies.forEach(function(enemy) {
            if (distance(enemy.x, enemy.y, point.x, point.y) <= enemy.strength+10) {
                point.danger += 5;
            }
        });
        if (distance(me.x, me.y, point.x, point.y) <= 2 && point.danger == 0) {
            point.danger--;
        }
    }
});
var bestPoint = points[0];
points.forEach(function(point) {
    if (point.danger < bestPoint.danger || (point.danger == bestPoint.danger && distance(point.x, point.y, destination.x, destination.y) < distance(bestPoint.x, bestPoint.y, destination.x, destination.y))) {
        bestPoint = point;
    }
});
return moveTo(bestPoint.x, bestPoint.y, this.strength);

Tries to get the flag. If someone else already got it, Flag Hunter walks towards the jail, either confusing the enemy or freeing his team members.

Blue - A jolly good fellow
First attempt both at programming in Javascript, and at code-golf.
It will chase anything that comes too close to the flag, trying to front-run their moves. Otherwise, it will run to rescue team-mates in jail, or lazily try to get to the other team's flag.
// Euclidean distance
var distance = function(p1,p2){
 return Math.sqrt( (p1.x - p2.x)**2 + (p1.y - p2.y)**2 );
}

// points from p1 to p2
var direction = function(p1, p2){
 return Math.atan2( p2.y - p1.y, p2.x - p1.x);
}

//moving
var move2 = function(dir, step){
    if(isNaN(dir)){   dir = 0; };
    if(isNaN(step)){ step = 0; };
    return {
        x: Math.cos(dir)*step,
        y: Math.sin(dir)*step
    };
}

var intercept_at = function(me, they, field){
    if ( distance(me, they)<me.strength ){
        return they;
    }

    //console.log("I am at (", me.x, me.y, ") ");
    //console.log("They are at (", they.x, they.y, ") ");

    //first goal
    if( field.my_flag.pickedUpBy == null ){
        their_goal = field.my_flag;
        eta = (distance(they, their_goal) - they.strength)/2;
        their_dir = direction(they, their_goal);
        for( var i=1; i<eta; i++){
          they_next = {
            x: they.x + Math.cos(their_dir)*(they.strength/2 + (i+1)*2),
            y: they.y + Math.sin(their_dir)*(they.strength/2 + (i+1)*2)
          };
          if( (distance(me, they_next) )<(1.95*i) ){
            //console.log("goal is flag at (", their_goal.x, their_goal.y, ") ");
            //console.log("I can reach it at (", they_next.x, they_next.y, ") in less than ", i);
            return they_next;
          }
        }
    // second goal
    }

    my_flag = field.my_flag;
    their_goal = { x: my_flag.x, y:field.h/2 - 5};
    eta = (distance(my_flag, their_goal) - they.strength)/2;
    their_dir = direction(my_flag, their_goal);
    for( var i=0; i<eta; i++){
        they_next = {
            x: my_flag.x + Math.cos(their_dir)*(they.strength/2 + (i+1)*2),
            y: my_flag.y + Math.sin(their_dir)*(they.strength/2 + (i+1)*2)
        };
        if( (distance(me, they_next) )<(1.95*i) ){
            //console.log("goal is escaping at (", their_goal.x, their_goal.y, ") ");
            //console.log("I can front-run it at (", they_next.x, they_next.y, ") in less than ", i);
            return they_next;
        }
    }
    //console.log("Goose chase at (", they.x, they.y, ") ");
    return they;
}

var intercept = function(me, they, field){
  they_at = intercept_at(me, they, field);
  they_at.y = Math.min(they_at.y, field.h/2-5)
  dist2me = distance(me, they_at);
  dir2me = direction(me, they_at);
  if ( dist2me<me.strength ){
    return move2(dir2me, dist2me);
  }else{
    return move2(dir2me, 2);
  }
}

var closest_enemy = function(my_flag, enemies){
    cur_tgt_num = null;
    cur_tgt_dst = 999;

    for( var i=0; i<enemies.length; i++){
      if(!enemies[i].isJailed){
        cur_dst = distance(enemies[i], my_flag);
        if ( cur_dst < cur_tgt_dst ){
          cur_tgt_dst = cur_dst;
          cur_tgt_num = i;
        }
      }
    }

    return enemies[cur_tgt_num];
}

var enemies_closer_than = function(enemies, radius, field){
    closer_than = 0;
    for( var i = 0; i<enemies.length; i++){
        if(!enemies[i].isJailed){
            closer_than = closer_than + ( distance(enemies[i], field.my_flag)<radius );
        }
    }
    return closer_than;
}

var team_jailed = function(team){
    for( var i = 0; i<team.length; i++){
        if(team[i].isJailed){
            return team[i];
        }
    }
    return null;
}

var bound_positions = function(p0, field){
    p0.x = Math.max(0, Math.min(p0.x, field.w));
    p0.y = Math.max(0, Math.min(p0.y, field.h));
    return p0;
}

var avoid_obstacle = function(me, goal, obstacle, field, can_run){
    //we know that there is a safe haven
    if( distance(me, goal)<me.strength && can_run){
        return move2(direction(me, goal), me.strength)
    }

    if( obstacle == null ){
        return move2(direction(me, goal), 2);
    }

    ob_dir = direction(me, obstacle);
    if( distance(me, obstacle) < Math.sqrt(2)*(4+obstacle.strength)){
        me_next1 = bound_positions({x: me.x - 4*Math.cos(ob_dir),y: me.y - 4*Math.sin(ob_dir)}, field);
        me_next2 = bound_positions({x: me.x - 4*Math.sin(ob_dir),y: me.y - 4*Math.cos(ob_dir)}, field);
        me_next3 = bound_positions({x: me.x - 4*Math.sin(ob_dir),y: me.y - 4*Math.cos(ob_dir)}, field);
        if( distance(goal, me_next1) < distance(goal, me_next2) ){
          if( distance(goal, me_next1) < distance(goal, me_next3) ){
            me_next = me_next1;
          }else{
            me_next = me_next3;
          }
        }else{
          if( distance(goal, me_next2) < distance(goal, me_next3) ){
            me_next = me_next2;
          }else{
            me_next = me_next3;
          }
        }

        //console.log("Escaping from (", obstacle.x, obstacle.y, ")");
        return move2(direction(me, me_next), 4);
    }

    eta = (distance(me, goal)/2);
    my_dir = direction(me, goal);
    me_next = me;
    i=0;
    while(i<eta && (distance(me_next, obstacle) > obstacle.strength+2*i)){
       i++;
       me_next = {x: me_next.x + i*Math.cos(my_dir),y: me_next.y + i*Math.sin(my_dir)};
       me_next = bound_positions(me_next, field);
       if( distance(me_next, obstacle) < obstacle.strength+2*i ){
         me_next1 = {x: me_next.x + i*Math.sin(ob_dir),y: me_next.y - i*Math.cos(ob_dir)};
         me_next2 = {x: me_next.x - i*Math.sin(ob_dir),y: me_next.y + i*Math.cos(ob_dir)};
         if( distance(goal, me_next1) > distance(goal, me_next2) ){
            me_next = bound_positions(me_next2, field);
         }else{
            me_next = bound_positions(me_next1, field);
         }
       }
    }
    if( distance(me_next, obstacle) > obstacle.strength+2*i ){
        //console.log("Trying to reach goal at (", goal.x, goal.y, ") by pointing at (",me_next.x, me_next.y,")");
        return move2(direction(me, me_next), 2);
    }

    //console.log("Waiting to reach (", goal.x, goal.y,")");
    my_dir = direction(me, goal);
    me_next = {
        x: me.x + Math.cos(my_dir)*6,
        y: me.y + Math.sin(my_dir)*6
    }
    for( var i=0; i<field.team.length; i++){
        me_next.x = me_next.x - Math.sign(field.team[i].x - me_next.x);
        me_next.y = me_next.y - Math.sign(field.team[i].y - me_next.y);
    }
    return move2(direction(me, me_next), Math.floor(Math.random() * 2));
}

var field = {
    w: WIDTH,
    h: HEIGHT,
    g: DEFENSE_RADIUS,
    my_flag: tFlag,
    their_flag: eFlag,
    team: team,
    enemies: enemies
    };

var n_enemy = enemies.length;

  if( enemies_closer_than(enemies, field.h*0.67, field)>0 || tFlag.pickedUpBy !== null){
    //console.log("My flag is in danger");

    // directive defend
    messages[123 + this.id] = 'defend_own_flag';
    if ( tFlag.pickedUpBy !== null ) {
      return intercept(this, tFlag.pickedUpBy, field);
    }else{
      return intercept(this, closest_enemy(tFlag, enemies), field);
    }
  }else{

    if( tJailed.length>0 ){

        // directive support
        console.log("rescueing team member");
        console.log(tJailed);
        return avoid_obstacle(this, tJailed[0], closest_enemy(this, enemies), field, 0);
    }else{

      // directive attack
      messages[123 + this.id] = 'capture_enemy_flag';
      if ( eFlag.pickedUpBy == null ){
        //console.log("Going to capture the flag");
        return avoid_obstacle(this, eFlag, closest_enemy(this, enemies), field, 0)

      }else if (this.id == eFlag.pickedUpBy.id){
        //console.log("I have the flag");
        return avoid_obstacle(this, {x:this.x, y:field.h/2 - 1}, closest_enemy(this, enemies), field, 1);

      }else {
        //console.log("Someone else has the flag");
        return avoid_obstacle(this, eFlag, closest_enemy(this, enemies), field, 0);

      }
    }
  }

return move2(0,0);


text:
Who wins a Spades trick
Write code to determine who wins a four-card trick in a game of Spades. Fewest bytes wins.
The input is a string that lists the four cards played in sequence like TH QC JH 2H (Ten of Hearts, Queen of Clubs, Jack of Hearts, Two of Hearts). A card is given by two characters: a suit from CDHS and a value from 23456789TJQKA. You are guaranteed that the input is valid and the cards are distinct.
You should output a number 1, 2, 3, or 4 for the winner of the trick. In the example TH QC JH 2H, the jack of hearts wins the trick, so you should output 3.
Your input and output must be exactly as described, except trailing newlines are optional.
Here are the Spades rules for winning a trick. The winning card is the highest card of the four, with some caveats. Spades is the trump suit, so any spade outranks any non-spade. The suit of the first card played is the lead suit, and only cards of that suit or spades are eligible to win the trick. Cards of the same suit are compared by their values, which are given in increasing order as 23456789TJQKA.
Test cases:
TH QC JH 2H
3
KC 5S QS 9C
3
QD 2D TD 5D
1
9S 5D AD QS
4
3D 4C 3H JH
1
9S 4S TS JS
4
5H 9H 2C AD
2
5S 4C 3H QD
1
2H 2S KH AH
2

Pyth, 28 27 25 bytes
J"KTAZ"hxcz)eo_XN+@z1JJcz

Try it online: Demonstration or Test Suite (first 4 chars are the test suite construct)
Thanks to @isaacg for a trick, which saved 2 chars.
The main idea is to modify chars of each hand such a in way, that the winning hand has the maximal value.
The values of the hands 23456789TJQKA is already nearly sorted. I just have to replace T with A, K with T and A with Z, resulting with 23456789AJQSZ.
The order of suits CDHSare for the most not really important. S, the most powerful suit, which is already the maximal value. Important is to give the suit of the first hand the second most powerful value. So I translate this suit into K.
All hands also have to be read reverse, since the suit is more powerful than the value.
                           implicit: z = input string
J"KTAZ"                    J = "KTAZ"
             o         cz  orders the hands N of split(z) by:
              _              the reversed of
               XN+@z1JJ      N, where the values z[1]+J are replaced by J
            e              last element (winning hand)
        xcz)               index of the winning hand in split(z)
       h                   + 1

I give up, well played :P

I don't think the .e stuff is worth it - using o is 1 character shorter as I figure it.

@isaacg Your right. Funny thing is, I had the 27 solution before the .e 28 solution. But the 27 solution ended with a ) and therefore also had 28 bytes.  :oops:

I thought of a way to save another 2 characters: Translate from +@z1"KTA" to "KTAZ", but instead of using the strings directly use J"KTAZ" at the beginning and +@z1J to J.

@isaacg Very clever. Thanks.
Btw. I thinking quite a while about making the 3rd argument of X optional (Only if a and b are strings). But I'm not really sure, if Xab) should evaluate to Xab_b (inverted b, would be nice for stuff like Xa"</\>") or Xab+tbhb (b shifted).  What your preference?

Hm. Well, since I was thinking of adding a rotate function to Pyth, probably .r, I'll use that for the latter behavior and the reversal for X with the third argument omitted. Both will have a 2 character overhead.

CJam, 34 33 bytes
lS/_{)2$0='S+\#\"TQKA"_$er+}$W>#)

Algorithm
The logic is simple. I have a custom sort going on, in which I first give priority to the second character representing the suit. In this, Spades gets the highest priority and then the first thrown suite. Rest all are -1. Then I sort on the first character with swapping of T with A and Q with K to have lexical sorting.
Code explanation
First off, lets see what is the lexical order of the face values of the cards:
"23456789TJQKA"$

23456789AJKQT

So, all numbers are at correct position. J is also at correct position. We need to swap K and Q and J and A to get lexical order.
lS/_{)2$0='S+\#\"TQKA"_$er+}$W>#)
lS/                                 "Read an input line and split on spaces";
   _{                      }$       "Copy the array and sort it using this custom logic";
     )                              "Take off the last character of each hand.";
      2$0=                          "Get the suit of the first hand";
          'S+                       "Add Spades suit to it";
             \#                     "Get the index of the current hand suit.
                                     1 for Spades, 0 for first hand suit, -1 otherwise";
               \                    "Put face value of this hand on top of stack";
                "TQKA"              "Put string TQKA on stack";
                      _$            "Copy and sort. This essentially reverses the string
                                     TQKA to form AKQT. This is 1 byte shorter than _W%";
                        er+         "Swap T with A and K with Q and add to the
                                     suit index calculated previously";
                                    "After the above tuple, sorting will automatically
                                     convert the tuple to string and sort lexically";
                             W>     "Get the array containing only the last element";
                               #)   "Get the index of this hand in original set and
                                     increment to convert it to 1 based";

Try it online here

JavaScript (ES6), 112
Scan the list and return the position of the highest value found.
Run snippet to test (in Firefox)

F=t=>t.split(' ').map((c,i)=>(n='23456789TJQKA'.search(c[0])+(c[1]>'H'?40:c[1]==t[1]&&20))>m&&(m=n,r=i+1),m=0)|r

C.innerHTML=['TH QC JH 2H','KC 5S QS 9C','QD 2D TD 5D','9S 5D AD QS','3D 4C 3H JH','9S 4S TS JS','5H 9H 2C AD','5S 4C 3H QD'].map(h=>h+' -> '+F(h)).join('\n')

Perl, 73 bytes
#!perl -pl
/\B./;s/$&/P/g;y/TKA/IRT/;$_=reverse;@a=sort split;/$a[-1]/;$_=4-"@-"/3

Try me.
Converts the card names so the game value order follows the alphabetical order, then picks the highest by sorting and looks for it in the original string for position.

Ruby, 59+2=61
With command-line flags na, run
p (1..4).max_by{|i|$F[i-1].tr($_[1]+'SJQKA','a-z').reverse}

J, 47 bytes
1+[:(i.>./)_3+/\16!@-]i.~'SXAKQJT9876543'1}~1&{

Usage:
   (1+[:(i.>./)_3+/\16!@-]i.~'SXAKQJT9876543'1}~1&{) 'TH QC 9S 8S'
3

Method:

For every input char we assign a value based in its position in the 'S[second char of input]AKQJT9876543' string. Non-found chars get the value last position + 1 implicitly.  Further characters have much less value (value=(16-position)!).
Compute the sum for the 3 input-char triplet and one duplet (e.g. TH_ QC_ 9S_and 8S).
Choose the 1-based index of the maximal value.

(J unfortunately can't compare chars or strings directly. It can only check for their equality which ruled out some other approaches for this challenge.)
Try it online here.

C#, 237
using System;namespace S{class P{static void Main(string[] a){var V="23456789TJQKA";int x=0;int y=0;var z=a[0][1];for(int i=0;i<4;i++){int q=V.IndexOf(a[i][0])+2;var w=a[i][1];q*=w==z?1:w=='S'?9:0;if(q>y){x=i;y=q;}}Console.Write(x+1);}}}

How it works:
 Iterate each hand to calculate the "value" of the card.. store the highest valued index.
A cards value is determined as the rank of the card multiplied by 0 if it is not a spade or the opening suit, 1 if it is the opening suit and 9 if it is a spade but not the opening suit.
 (9 choosen b/c 2*9=18> A=14 & 9 is a single char)

Pyth, 36 33 bytes
KczdhxKeo,x,ehK\SeNXhN"TKA""AYZ"K

Fairly straightforward approach, uses sorting with a custom key function, then finds the index of the highest value.

Did you try avoiding the sort and just find the highest value? In JavaScript that turned out to be shorter

@edc65 In Pyth there is no operation to find the highest value, just to sort. But with one character (e) you can get the last element, so finding the highest value is just sorting followed by getting the last element.

Downvoter, care to explain?

Pyth, 31 bytes
hxczdeo}\SNo}@z1Zox"TJQKA"hNScz

Try it here.
How it works:
The proper way to read this procedure is back to front. The procedure sorts the desired card to the end of the list, then pulls it out and finds its index in the original list.

cz: This generates the list of card strings. c, chop, is normally a binary function (arity 2), but when called on only one input, serves as the .split() string method.
S: This applies the normal sorting behavior, which sorts lower numbered cards before higher ones.
ox"TJQKA"hN: This orders the cards by the index (x) in the string "TJQKA" of the first letter of the card (hN). For cards with numbers, the first letter is not found, giving the result -1. Since Pyth's sorting function is stable, the numbered cards' order is not affected.
o}@z1Z: Next we order by whether the suit of the first card played (@z1) is in the card in question. Since True sorts behind False, this sends cards of the lead suit to the back.
o}\SN: This is the same as the sort before, but it sorts on whether the letter S is in the card, sending spades to the back.
hxczde: This extracts the last card sorted this way (e), finds its index in the list of cards (xczd) and increments by 1 (h), giving the desired player location.

 Python, 172 bytes
l=input().split(" ")
s="23456789TJQKA"
h=l[0]
for c in l:
  if c[1] not in [h[1],"S"]:
    continue
  if s.index(h[0])>s.index(c[0]):
    continue
  h=c
print(l.index(h)+1)

There wasn't a Python answer here, so I fixed that :)
Simply compares the cards, discarding them if they are of a different suit to the current highest (and not a spade), then if they are of a lower value. At the end, simply get the highest card, and add 1 to its index.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Quick! Escape the black hole!
It is the year 87,539,319 and solitary space-walking is now commonplace, many people travel into space by themselves, propelled by nothing but a jetpack on their backs, programming their course with a personal computer and keyboard as they go.
You are one such person; you were out on a lovely, peaceful spacewalk, when, all of a sudden, you were ensnared by the gravity of a black hole!
As you plummet towards this black hole, spiraling ever faster inwards, you realise your one chance of survival is to broadcast a distress message, and hope a nearby ship comes to rescue you.
So, you break out your keyboard, and begin typing away a program.
Your program can be in any language, and must print HELP! to stdout (your PC broadcasts all stdout far into the depths of space.)
However, as you are near a blackhole, your keyboard is slowly being ripped to shreds!
Assume you are using a QWERTY keyboard like the one below, and that the blackhole is to your left;

Remember, left and right shift are two different keys.
after every keypress, the left-most row of your keyboard (keys covered by left-most red line) is ripped off and flung into the black hole!
So, your first keypress could be any key on the keyboard, but from then onwards none of the leftmost Tab, Caps, Shift, Ctrl or ` keys may be used, at all. (r-shift and r-ctrl can still be used)
After the next keypress, the keys 1, Q, A,Z and Alt are flung into the abyss, and may not be used thereafter. After that, you lose Space, X, S, W, 2 and so forth.
Obviously, you want to complete your program as quickly as possible, so that rescue-time is increased; therefore, this is code-golf, and the shortest program in key presses wins!
Each answer should provide a list of keypresses, so, if my answer was this program (in the language squardibblyack)
!HELP\.

a keylist could look like:
Shift!HELP release shift \.
length: 8
I'm worried this challenge might be too difficult, but I'd love to see the kinds of answers submitted!

Downvote? I would much rather some feedback.

I'm downvoting this because it feels too constrained to have much creativity.

@trichoplax Your right shift?

@trichoplax I think I've cleared all mentioned ambiguities, are there any more I should "iron out"?

I've deleted my comments that you have now addressed, and this looks much better. Your link to my comment will no longer work since I've deleted the comment, so you might need to edit that back to normal text.

Can we assume that using the python shell without print qualifies as STDOUT?

I've never before seen a challenge here with such a small max character limit. 13 or fewer (more like 10-11 if you need shift and don't end with )

What if my keyboard has a number pad?

This could be slightly better with arrow keys.

I don't see why people are still voting to close this question as unclear. How much ever restrictive/difficult be the challenge, its pretty clear after the recent edits.

Is caps lock still effective if it's been pressed although the key has disappeared?

@JoshCaswell I would assume so, since you don't need to hold it down. Test it on your keyboard. You'll need to find a black hole, first. But it's probably better to hold rt. shift instead...

I give up if I can't use my keyboard's number pad. I haven't found another language that can do what CJam did in the same code length.

I had the great idea to use GoLunar, but it's still too long... :(

You know what they say about assumptions, @mbomb007.

Agreed with @isaacg, if the char limit tempo was slower this could make for an interesting challenge, but now it's getting a few answers at best instead.

What are the rules on derivative puzzles? I thought of a more relaxed challenge ("touch-typist's edition" - releasing modifier keys is free, and you can press one key with each hand [in any order] per cycle) that might get more responses.

CJam, 11 keystrokes
The code is
"HELP*")9-

and the keylist is
Shift"HELP*") release shift 9-
and here is a demonstration of how it looks:

and here is how the code works:
"HELP*"              "This puts the string HELP* on stack";
       )             "This takes out the last character of the string and puts it
                      on the stack as a character";
        9-           "This simply reduces 9 from the ASCII code of * character
                      present on the stack which makes it an !";
                     "CJam automatically prints everything that is on stack";

Try the code here

Using the asterisk was pretty clever! I'd never thought of that.

Well, I was unable to do this in GolfScript. It's a little too long. Converting from an integer to ascii is inefficient. "HELP*")9-[]+''+. I can't type the last four.

I just knew CJam would have an answer...

So one of the most future-proof languages in the world is apparently CJam.

Watch your finger when you hit the E, it looks like it might get taken into the abyss!

@CanadianLuke and 9

Great graphical representation!  Never heard of CJam, though.

@vapcguy You must be new. It's an esoteric programming language used only for code-golf AFAIK. The best/only way to learn it is to view existing code in answers on this site, or to view the home page: http://sourceforge.net/p/cjam/wiki/Home/

rs, 10 keystrokes (assumes the user is using Nano)
Or equivalent editor where Shift doesn't select text.
This isn't really a programming language, but if sed can be used on Code Golf, then rs can be used.
Right Shift ! Left E Left H Right L P Enter
HELP!

It just replaces the empty string with "HELP!", effectively printing it to the screen. Roughly equivalent to the sed script:
s/^/HELP!/

The cool part is that rs automatically puts ^/ in front of a replacement pattern where the delimiter (/) is not found. Handy for indenting code.

You forget that Enter is a stroke, too. 10 strokes.

@vapcguy Right. Fixed.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Factoring a 64-bit integer
Write a GOLF assembly program that reads an integer from stdin (followed by a trailing newline), and outputs its prime factors seperated by newlines, followed by a trailing newline on stdout.
The prime factors need not be in a particular order. 1 is not a prime factor.
Your GOLF binary (after assembling) must fit in 8192 bytes.

Your program will be scored by running it 10 times, each with one of the following inputs:
8831269065180497
2843901546547359024
6111061272747645669
11554045868611683619
6764921230558061729
16870180535862877896
3778974635503891117
204667546124958269
16927447722109721827
9929766466606501253

These numbers are roughly sorted in terms of difficulty. The first one should easily be solvable by trial division.
Optimization towards this set of numbers is against the spirit of the question, I may change the set of numbers at any point. Your program must work for any positive 64-bit input number, not just these.
Your score is the sum of CPU cycles used to factor the above numbers.

Because GOLF is very new I'll include some pointers here. You should read the  GOLF specification with all instructions and cycle costs. In the Github repository example programs can be found. In particular look at the factorial example program, which demonstrates input/output.
Compile your program to a binary by running python3 assemble.py your_source.golf. Then run your program using python3 golf.py your_source.bin, this should print the cycle count as well. See the values of the register contents at program exit with the -d flag - use --help to see all flags.

About golf: what do you mean by "Signed division and modulus work like they do in Python - the sign of the result is the same as the sign of the divisor"? -4/-2 should be -2? (I don't think so)

@edc65 Sorry, the sign portion only applies to  modulus, I'll edit the docs.

Just a friendly reminder that comments are not meant for extended discussion. I've migrated the comments to chat and cleaned them up here.

If the program must work for any 64-bit input integer, what happens if the input is prime? Since 1 is not a prime factor, should it only print the input integer?

@mbomb007 Correct, it should only print the input integer.

I really want to use SQUFOF on this one, but it just so happens that the second-to-last test case is one of the ~2% of numbers (of that difficulty) that fail to factor without a multiplier.  What modifications would you consider "optimization towards this set of numbers"?

@2012rcampion I think having fallback algorithms is fine, but at every stage your program must be general for all numbers. I'm sorry that 2% of the input space is so overrepresented for the scoring of your answer though =/

SQUFOF does succeed eventually on all numbers (if it fails in one round, you try again with a different multiplier), but it takes a long time to fail on the first round.  If I started with a multiplier, that would cut my time on that particular test case by 50-70%.  However, I feel like that's cheating since the average time over all numbers would stay the same.  (I'm probably going to end up using Pollard-Brent rho factorization anyway, it doesn't require any expensive square roots.)

2,279,635 cycles—7373 bytes (deterministic)
One-by-one:
robert@unity:~/golf-cpu/factor$ ./test.sh
13
23
31
37
41
47
47
59
61
79
Execution terminated after 1088 cycles with exit code 0.
2
2
2
2
3
3
107
164546579
1121707
Execution terminated after 41325 cycles with exit code 0.
3
3
3
7
7
7
13
50759273983933
Execution terminated after 9413 cycles with exit code 0.
7
7
7
13
250250521
2531
4091
Execution terminated after 22282 cycles with exit code 0.
31
89
97
357653
3881
18211
Execution terminated after 47656 cycles with exit code 0.
2
2
2
3
702924188994286579
Execution terminated after 17423 cycles with exit code 0.
7
103
7209485975851
727
Execution terminated after 15973 cycles with exit code 0.
1920043
66449
1604167
Execution terminated after 153683 cycles with exit code 0.
52528036667
322255481
Execution terminated after 1952229 cycles with exit code 0.
9929766466606501253
Execution terminated after 18563 cycles with exit code 0.
robert@unity:~/golf-cpu/factor$

Summary:
robert@unity:~/golf-cpu/factor$ ./test.py factor.golf factors_testset
binary length: 7373 bytes
10/10 passed in 0:00:08.53 s
2,279,635 cycles (227963.50 average)
(267.14 KCPS average)

       0 ######################################################################
  100000 ########
  200000
  300000
  400000
  500000
  600000
  700000
  800000
  900000
 1000000
 1100000
 1200000
 1300000
 1400000
 1500000
 1600000
 1700000
 1800000
 1900000 ########
robert@unity:~/golf-cpu/factor$

I use a combination of trial division and the Brent-Pollard rho algorithm for factorization, and table lookup plus Miller-Rabin for primality testing.  I'll add some more explanation tomorrow.
Note that because of the character limit on post length, the second data table is truncated.  This gist includes the full table.
primes_53 = \
  b'\x03\x05\x07\x0b\x0d\x11\x13\x17\x1d\x1f\x25\x29\x2b\x2f\x35\x3b' \
  b'\x3d\x43\x47\x49\x4f\x53\x59\x61\x65\x67\x6b\x6d\x71\x7f\x83\x89' \
  b'\x8b\x95\x97\x9d\xa3\xa7\xad\xb3\xb5\xbf\xc1\xc5\xc7\xd3\xdf\xe3' \
  b'\xe5\xe9\xef\xf1\xfb'

# for 2**16+1:2:2**17-1, 1 if prime, 0 otherwise
prime_bytes = \
  b'\x8b\x24\x60\x82\x10\x41\x81\x12\x40\x08\x26\x0d\x03\x00\x01\x41' \
  ...
  b'\x41\x30\x20\x10\x00\x00\x80\x00\x40\x50\x24\x00\x83\x00\x01\x8a'

main:
  call input

# check if input is 1
  cmp c, n, 1
  sz c, 3
    mov o, n
    call print
    halt 0

# remove factors of two
  mov o, 2
  div_2_loop:
    and c, n, 1
    snz c, 3
      call print
      shr n, n, 1
      jmp div_2_loop

# check if n is a power of two
  cmp c, n, 1
  sz c, 1
    halt 0

# trial division
  mov d, data(primes_53)
  mov i, 53

  trial_division_loop:
    lbu p, d
    trial_division_check:
      divu q, r, n, p
      snz r, 4
        mov o, p
        call print
        mov n, q
        jmp trial_division_check
    mulu s, t, p, p
    leu c, n, s
    sz c, 5
      cmp c, n, 1
      snz c, 2
        mov o, n
        call print
      halt 0
    sub i, i, 1
    add d, d, 1
    jnz trial_division_loop, i

  # mov g, 0  # initialize factor list pointers
  # mov h, 0  # all registers are zero at program start

  # *g is the next factor to check for primality
  # *h is the last factor we've found so far
  # the first factor is always *0

  sw g, n

prime_test:

  # by this point we know that n has no prime factors less than 256,
  # so if n is less than 256**2, then it must be prime
  lequ c, n, 2**16
  jnz is_prime, c

  geu c, n, 2**17+1
  jnz miller_rabin, c

  sub d, n, 2**16+1  # table starts at 2**16+1 (by above argument)
  shr d, d, 1  # we know n is odd, so we ignore the last bit
  and m, d, 2**3-1  # each byte is 3-bit lookup table
  shr d, d, 3
  add d, d, data(prime_bytes)
  lbu p, d
  shr p, p, m
  and p, p, 1
  jnz is_prime, p

  jmp pollard_rho  # I should probably do trial division here
                   # since we only have around 20 more primes to check

################
# Miller-Rabin primality test; bases from https://miller-rabin.appspot.com/
# Note that this subroutine, as well as most of the ones before the 'utility
# functions' section are not proper functions, as they sometimes jump directly
# to the next step instead of returning!
#
# input: n
# output: n/a
################
miller_rabin:
  shr d, n, 1
  mov b, 1
  mr_rd_loop:  # n - 1 == d * 2**b, d is odd
    and c, d, 1
    snz c, 3
      shr d, d, 1
      inc b
      jmp mr_rd_loop

  geu c, n, 2**32-1  # test if we can use single-precision arithmetic
  jnz miller_rabin_montgomery, c

  sub m, n, 1

  mr_test_1:
    gequ c, n, 0x000000000005361b
    jnz mr_test_2, c

    mov a, 0x81b33f22efdceaa9
    call miller_rabin_test

    jmp is_prime

  mr_test_2:
    gequ c, n, 0x000000003e9de64d
    jnz mr_test_3, c

    mov a, 0x0000004e69b6552d
    call miller_rabin_test

    mov a, 0x00223f5bb83fc553
    call miller_rabin_test

    jmp is_prime

  mr_test_3:
    mov a, 0x3ab4f88ff0cc7c80
    call miller_rabin_test

    mov a, 0xcbee4cdf120c10aa
    call miller_rabin_test

    mov a, 0xe6f1343b0edca8e7
    call miller_rabin_test

    jmp is_prime

miller_rabin_montgomery:
  call montgomery_precompute
  sub m, n, r  # montgomery representation of n-1

  mr_test_mt_3:
    gequ c, n, 0x000000518dafbfd1
    jnz mr_test_mt_4, c

    mov a, 0x3ab4f88ff0cc7c80
    call miller_rabin_test_montgomery

    mov a, 0xcbee4cdf120c10aa
    call miller_rabin_test_montgomery

    mov a, 0xe6f1343b0edca8e7
    call miller_rabin_test_montgomery

    jmp is_prime

  mr_test_mt_4:
    gequ c, n, 0x0000323ee0e55e6b
    jnz mr_test_mt_5, c

    mov a, 0x0000000000000002
    call miller_rabin_test_montgomery

    mov a, 0x0000810c207b08bf
    call miller_rabin_test_montgomery

    mov a, 0x10a42595b01d3765
    call miller_rabin_test_montgomery

    mov a, 0x99fd2b545eab5322
    call miller_rabin_test_montgomery

    jmp is_prime

  mr_test_mt_5:
    gequ c, n, 0x001c6b470864f683
    jnz mr_test_mt_6, c

    mov a, 0x0000000000000002
    call miller_rabin_test_montgomery

    mov a, 0x000003c1c7396f6d
    call miller_rabin_test_montgomery

    mov a, 0x02142e2e3f22de5c
    call miller_rabin_test_montgomery

    mov a, 0x0297105b6b7b29dd
    call miller_rabin_test_montgomery

    mov a, 0x370eb221a5f176dd
    call miller_rabin_test_montgomery

    jmp is_prime

  mr_test_mt_6:
    gequ c, n, 0x081f23f390affe89
    jnz mr_test_mt_7, c

    mov a, 0x0000000000000002
    call miller_rabin_test_montgomery

    mov a, 0x000070722e8f5cd0
    call miller_rabin_test_montgomery

    mov a, 0x0020cd6bd5ace2d1
    call miller_rabin_test_montgomery

    mov a, 0x009bbc940c751630
    call miller_rabin_test_montgomery

    mov a, 0x0a90404784bfcb4d
    call miller_rabin_test_montgomery

    mov a, 0x1189b3f265c2b0c7
    call miller_rabin_test_montgomery

    jmp is_prime

  mr_test_mt_7:
    mov a, 0x0000000000000002
    call miller_rabin_test_montgomery

    mov a, 0x0000000000000145
    call miller_rabin_test_montgomery

    mov a, 0x000000000000249f
    call miller_rabin_test_montgomery

    mov a, 0x0000000000006e12
    call miller_rabin_test_montgomery

    mov a, 0x000000000006e0d7
    call miller_rabin_test_montgomery

    mov a, 0x0000000000953d18
    call miller_rabin_test_montgomery

    mov a, 0x000000006b0191fe
    call miller_rabin_test_montgomery

    jmp is_prime

  is_prime:
    mov o, n
    call print
    cmp c, g, h
    sz c, 1
      halt 0
    add g, g, 8
    lw n, g
    jmp prime_test

  found_factor:
    divu n, b, n, a
    add h, h, 8
    sw h, a
    jmp prime_test

################
# Miller-Rabin primality test subroutine; needs m == n - 1
#
# input: a, n, m
# output: n/a
################
miller_rabin_test:
  divu q, a, a, n  # a = a mod n
  snz a, 1
    ret  # a certifies primality if a == 0 mod n
  call power  # a = a**d mod n
  cmp c, a, 1  # r == 1
  sz c, 1
    ret  # a certifies primality if a**d == 1 mod n
  cmp c, a, m  # m == n-1
  sz c, 1
    ret  # a certifies primality if a**d == -1 mod n

  mov d, 2
  mr_square_loop:
    dec b
    jz pollard_rho, b
    mulu x, y, a, a  # a = a**2 mod n
    divu q, a, x, n  # q is unused
    cmp c, a, 1  # r == 1
    jnz pollard_rho, c  # a witnesses compositeness if a**(d*2**i) == 1 mod n
    cmp c, a, m  # m == n-1
    sz c, 1
      ret  # a certifies primality if a**(d*2**i) == -1 mod n
    jmp mr_square_loop

################
# Miller-Rabin primality test subroutine using Montgomery arithmetic; needs
# the values from the precomputation step as well as m == n - 1
#
# input: a, n, m, (u, v, r, s)
# output: n/a
################
miller_rabin_test_montgomery:
  divu q, a, a, n  # a = a mod n
  snz a, 1
    ret  # a certifies primality if a == 0 mod n
  mulu x, y, a, s
  call montgomery_reduce  # convert a to montgomery form
  mov a, x
  call montgomery_power  # a = a**d mod n
  cmp c, a, r  # r == 1 (mongtomery form)
  sz c, 1
    ret  # a certifies primality if a**d == 1 mod n
  cmp c, a, m  # m == n-1 (montgomery form)
  sz c, 1
    ret  # a certifies primality if a**d == -1 mod n

  mr_mt_square_loop:
    dec b
    jz pollard_rho_montgomery, b
    mulu x, y, a, a  # a = a**2 mod n
    call montgomery_reduce
    mov a, x
    cmp c, a, r  # r == 1 (mongtomery form)
    jnz pollard_rho_montgomery, c  # a witnesses compositeness if a**(d*2**i) == 1 mod n
    cmp c, a, m  # m == n-1 (montgomery form)
    sz c, 1
      ret  # a certifies primality if a**(d*2**i) == -1 mod n
    jmp mr_mt_square_loop

################
# Pollard-Brent rho factorization algorithm
#
# input: n
# output: n/a
################
pollard_rho:

  rho_skip_count = 64

  mov o, 42
  rho_retry:

  mov b, o
  mov j, 1
  mov f, 1
  mov d, 1
  rho_outer_loop:
  mov a, b
    mov i, j
    rho_fast_loop:
      mulu b, y, b, b
      add b, b, 1
      divu y, b, b, n
      #mov o, b
      #call print
      sub i, i, 1
      jnz rho_fast_loop, i
    mov k, 0
    rho_slow_loop:
      mov e, b
      sub i, j, k
      leu c, rho_skip_count, i
      sz c, 1
        mov i, rho_skip_count
      rho_inner_loop:
        mulu b, y, b, b
        add b, b, 1
        divu y, b, b, n
        leu c, a, b
        sz c, 1
          sub x, b, a
        snz c, 1
          sub x, a, b
        mulu f, y, x, f
        divu y, f, f, n
        #add o, f, 1000000000
        #call print
        sub i, i, 1
        jnz rho_inner_loop, i
      mov x, f
      call gcd
      mov d, x
      #mov o, d
      #call print
      add k, k, rho_skip_count
      gequ c, k, j
      snz c, 2
        lequ c, d, 1
        jnz rho_slow_loop, c
    shl j, j, 1
  lequ c, d, 1
  jnz rho_outer_loop, c

  cmp c, d, n
  sz c, 12
    rho_final_loop:
      mulu e, y, e, e
      add e, e, 1
      divu y, e, e, n
      #add o, e, 2000000000
      #call print
      leu c, a, e
      sz c, 1
        sub x, e, a
      snz c, 1
        sub x, a, e
      call gcd
      mov d, x
      #mov o, d
      #call print
      lequ c, d, 1
      jnz rho_final_loop, c

  cmp c, d, n
  sz c, 2
    add o, o, 1
    jmp rho_retry

  mov a, d
  jmp found_factor

################
# Pollard-Brent rho factorization algorithm using Montgomery arithmetic.
# Requires m = n - r
#
# input: n, (u, v, r, s, m)
# output: n/a
################
pollard_rho_montgomery:

  rho_mt_skip_count = 64

  mov o, 42
  rho_mt_retry:

  mulu x, y, o, s
  call montgomery_reduce
  mov b, x
  mov j, 1
  mov f, r
  mov d, 1
  rho_mt_outer_loop:
  mov a, b
    mov i, j
    rho_mt_fast_loop:
      mulu x, y, b, b
      call montgomery_reduce
      mov b, x
      geu c, b, m
      sz c, 1
        sub b, b, m
      snz c, 1
        add b, b, r
      #mov o, b
      #call print
      sub i, i, 1
      jnz rho_mt_fast_loop, i
    mov k, 0
    rho_mt_slow_loop:
      mov e, b
      sub i, j, k
      leu c, rho_mt_skip_count, i
      sz c, 1
        mov i, rho_mt_skip_count
      rho_mt_inner_loop:
        mulu x, y, b, b
        call montgomery_reduce
        mov b, x
        geu c, b, m
        sz c, 1
          sub b, b, m
        snz c, 1
          add b, b, r
        leu c, a, b
        sz c, 1
          sub x, b, a
        snz c, 1
          sub x, a, b
        mulu x, y, x, f
        call montgomery_reduce
        mov f, x
        sub i, i, 1
        jnz rho_mt_inner_loop, i
      mov x, f
      #mov o, x
      #call print
      call gcd
      mov d, x
      #mov o, d
      #call print
      add k, k, rho_mt_skip_count
      gequ c, k, j
      snz c, 2
        lequ c, d, 1
        jnz rho_mt_slow_loop, c
    shl j, j, 1
  lequ c, d, 1
  jnz rho_mt_outer_loop, c

  cmp c, d, n
  sz c, 15
    rho_mt_final_loop:
      mulu x, y, e, e
      call montgomery_reduce
      mov e, x
      geu c, e, m
      sz c, 1
        sub e, e, m
      snz c, 1
        add e, e, r
      leu c, a, e
        sz c, 1
          sub x, e, a
        snz c, 1
          sub x, a, e
      call gcd
      mov d, x
      lequ c, d, 1
      jnz rho_mt_final_loop, c

  cmp c, d, n
  sz c, 2
    add o, o, 1
    jmp rho_mt_retry

  mov a, d
  jmp found_factor

################ UTILITY FUNCTIONS ################

################
# Loads a decimal number terminated by a newline from stdin to register n.
#
# inputs:  none
# outputs: n
################
input:
  lw c, -1
  input_add_digit:
    sub c, c, ord('0')
    mov o, c
    mulu n, h, n, 10
    add n, n, c
    lw c, -1
    cmp q, c, ord('\n')
    jz input_add_digit, q
  ret n

################
# Prints the value of register o to stdout in decimal, followed by a newline.
#
# inputs:  o
# outputs: none
################
print:
  call print_char
  sw -1, ord('\n')
  ret

  print_char:
    divu o, x, o, 10
    sz o, 1
      call print_char
    add x, x, ord('0')
    sw -1, x
    ret

################
# Precomputes values used for Montgomery multiplication:
#  * u = 1/2**64 mod n
#  * v = -1/n mod 2**64
#  * r = 2**64 mod n  (montgomery representation of 1)
#  * s = 2**128 mod n (montgomery representation of 2**64)
#
# inputs: n
# outputs: u, v, s, t
################
montgomery_precompute:
  # first compute the inverses; based on xbinGCD from
  # http://www.hackersdelight.org/MontgomeryMultiplication.pdf
  # This step takes something like an average of 7 cycles per bit in the
  # 'fast' mode, and 8 cycles per bit in 'safe' mode, for a total of around
  # 500 cycles: but we only have to do it once per modulus

  mov u, 1
  mov v, 0
  mov i, 64
  # HD defensively computes (u+beta)/2 to avoid overflow, taking two extra
  # instructions; however, since u < beta overflow is only possible when
  # beta >= 2**63, in most cases we can use a faster version and save
  # 2 * 64 = 128 cycles, at the expense of a couple cycles comparison
  gequ c, n, 2**63
  jz mt_pre_gcd_loop, c
  mt_pre_gcd_loop_safe:
    dec i
    and c, u, 1
    snz c, 3
      shr u, u, 1
      shr v, v, 1
    sz 0, 6
      and c, u, n
      xor u, u, n
      shr u, u, 1
      add u, u, c
      shr v, v, 1
      add v, v, 2**63
    jnz mt_pre_gcd_loop_safe, i
    jmp mt_pre_gcd_end
  mt_pre_gcd_loop:
    dec i
    and c, u, 1
    snz c, 3
      shr u, u, 1
      shr v, v, 1
    sz 0, 4
      add u, u, n
      shr u, u, 1
      shr v, v, 1
      add v, v, 2**63
    jnz mt_pre_gcd_loop, i
  mt_pre_gcd_end:

  # compute 2**64 mod n; since 2**64 is too large to fit in a register, we
  # first calculate r = 2**63 mod n, if it's greater than n/2, r = 2r - n,
  # otherwise just r = 2r

  divu q, r, 2**63, n # q is unused
  shr c, n, 1
  geu c, r, c
  shl r, r, 1
  sz c, 1
    sub r, r, n

  # It would be entirely possible to compute 2**128 mod n by starting with
  # r and using repeated doubling (64 times); this would take something
  # like 4*64 = 256 cycles.  Instead I'll use a doubleword division
  # algorithm from Hacker's Delight (ch. 9-4, fig. 9-3), which takes
  # fewer than 100 cycles.

  mov l, 0
  # normalize the divisor (n)
  and c, n, 2**64 - 2**32
  snz c, 2
    shl n, n, 32
    add l, l, 32
  and c, n, 2**64 - 2**48
  snz c, 2
    shl n, n, 16
    add l, l, 16
  and c, n, 2**64 - 2**56
  snz c, 2
    shl n, n, 8
    add l, l, 8
  and c, n, 2**64 - 2**60
  snz c, 2
    shl n, n, 4
    add l, l, 4
  and c, n, 2**64 - 2**62
  snz c, 2
    shl n, n, 2
    add l, l, 2
  and c, n, 2**64 - 2**63
  snz c, 2
    shl n, n, 1
    add l, l, 1
  # normalize the numerator
  shl a, r, l
  # split the divisor into halfwords
  shr b, n, 32
  and m, n, 2**32 - 1
  # compute first halfword of remainder
  divu q, p, a, b
  mt_pre_div_adjust1: # loop runs at most two times, 035x on average
    gequ c, q, 2**32
    snz c, 4
      mulu d, f, q, m # f is unused
      shl c, p, 32
      geu c, d, c
      sz c, 4
        sub q, q, 1
        add p, p, b
        leu c, p, 2**32
        jnz mt_pre_div_adjust1, c
  shl a, a, 32
  mulu d, f, q, n
  sub a, a, d
  # compute second halfword of remainder
  divu q, p, a, b
  mt_pre_div_adjust2:
    snz c, 4
      mulu d, f, q, m
      shl c, p, 32
      geu c, d, c
      sz c, 4
        sub q, q, 1
        add p, p, b
        leu c, p, 2**32
        jnz mt_pre_div_adjust2, c
  shl a, a, 32
  mulu d, f, q, n
  sub a, a, d
  # de-normalize remainder
  shr s, a, l

  ret u, v, r, s

################
# Performs the Montgomery reduction step, x = [yx]/2**64 mod n
# Requres the u and v calculated in mongomery_precompute.
#
# inputs: x, y, n, (u, v)
# outputs: x
################
montgomery_reduce:
  mulu m, u, x, v  # m = ([yx] mod 2**64) / (-n) mod 2**64
  mulu z, w, m, n  # [wz] = mN
  add x, x, z      # [yx] += [wz]
  leu c, x, z      # this is where I really miss an ADC instruction
  sz c, 1
    inc w
  add x, y, w      # x = [yx] / 2**64 = y (combined with y+w from above)
  leu c, x, y      # x -= n if overflow
  sz c, 1
    sub x, x, n
  gequ c, x, n     # if x >= n
  sz c, 1
    sub x, x, n    # x -= n
  ret x

################
# Computes a = a**d mod n by repeated squaring.
#
# inputs: a, d, n
# outputs: a
################
power:
  mov b, a
  mov a, 1
  mt_pow_loop:
    and c, d, 1
    sz c, 2
      mulu x, y, a, b  # a = a*b mod n
      divu q, a, x, n  # q is unused
    mulu x, y, b, b  # b = b*b mod n
    divu q, b, x, n
    shr d, d, 1
    jnz mt_pow_loop, d
  ret a

################
# Uses Montgomery multiplication to compute a = a**d mod n.  Treats d as an
# ordinary unsigned integer; treats d as an integer in Montgomery form.
# Requres the u, v, and r calculated in mongomery_precompute.
#
# inputs: a, d, n, (u, v, r)
# outputs: a
################
montgomery_power:
  mov b, a
  mov a, r
  pow_loop:
    and c, d, 1
    sz c, 3
      mulu x, y, a, b
      call montgomery_reduce
      mov a, x
    mulu x, y, b, b
    call montgomery_reduce
    mov b, x
    shr d, d, 1
    jnz pow_loop, d
  ret a

################
# Computes x = GCD(x,n) using the binary GCD algorithm.  Assumes that x < n
# and that n is odd.  Note that we don't need a separate Montgomery GCD,
# since, surprisingly, GCD(x*(2**64) mod n, n) == GCD(x, n).
#
# inputs: x, n
# outputs: x
################
gcd:
  snz x, 2  # GCD(0, n) == n
    mov x, n
    ret x

  gcd_loop:
    and c, x, 1  # n is odd, so the GCD has no factors of two
    snz c, 3
    gcd_div_2_loop:
      shr x, x, 1
      and c, x, 1
      jz gcd_div_2_loop, c

    geu c, n, x
    sz c, 5
      sub x, n, x
      sub n, n, x
      jnz gcd_loop, x
        mov x, n
        ret x

    sub x, x, n
    jnz gcd_loop, x
      mov x, n
      ret x

You should definitely include a fully working and testable example, so please do include the table in some way or form.

@orlp Do you have access to Mathematica?  I can easily include the code I used to generate the table.

I do not. I think putting a dump of the full untruncated code on http://gist.github.com/ would be fine however.

As for your implementation, I would recognize my code in my sleep :) The mov o, 42 is a dead giveaway.

@orlp Thanks for reminding me about gist.  And actually, the 42 happens to be a coincidence; I copied the algorithm from the original paper.  Great minds think alike and all that...

That is an incredible coincidence. Would you mind joining me in the chat for a while?

Total 36,757,269,913 cycles
830B assembled
Number                Time (s)  Cycles
    8831269065180497       0.1         1148
 2843901546547359024      55.0      9535194
 6111061272747645669     351.4     60559378
11554045868611683619       0.8       135135
 6764921230558061729       1.0       155407
16870180535862877896   43067.5   7126449414
 3778974635503891117     148.7     22823483
  204667546124958269      87.4     13635943
16927447722109721827   16119.0   2739172134
 9929766466606501253  156158.3  26784802677

Factorization by trial division, with a few optimizations.
Probably not the fastest, but as no one else has posted yet, I'll kick it off.
main:
    call read
    call factor
    halt 0

# Prints factors. Pass number to be factored in register `a'.
factor:
    mov n, a # Write routine expects factor in `a', so we'll just keep it there.
    # Handle 2 specially
_factor_twos:               # do {
    geu b, n, 1
    jz _factor_ret, b   #   if (number <= 1) return
    and b, n, 1
    jnz _factor_rest, b #   if (number & 1 != 0) break
    mov a, 2
    call write          #   printf("%llu\n", 2)
    shr n, n, 1         #   number >>= 1
    jmp _factor_twos    # } while (0)
_factor_rest:
    mov a, 3            # factor = 3
_factor_rest_loop:          # do {
    cmp b, n, 1
    jnz _factor_ret, b  #   if (number == 1) return
    divu b, c, n, a     #   (quotient, remainder) = number / factor
    jnz _factor_not_divisible, c # if (remainder == 0) {
    call write                   #   printf("%llu\n", factor)
    mov n, b                     #   number = quotient
    jmp _factor_rest_loop
_factor_not_divisible:               # } else {
    leu c, b, a
    jnz _factor_print_last, c    #   if quotient < a, print n and return.
    add a, a, 2                  #   else a += 2 }
    jmp _factor_rest_loop # } while (0)
_factor_print_last:
    mov a, n
    call write # printf("%llu", n)
_factor_ret:
    ret

# Read stdin. Must be one decimal string, ending with a newline.
# Behavior on invalid input is unspecified.
# Return value stored in a.
read:
    mov a, 0
_read_loop_start:                # do {
    lw c, 0xffffffffffffffff #   c = getchar()
    sub b, c, ord('\n')
    jz _read_ret, b          #   if (c == '\n'), return
    sub c, c, ord('0')       #   c -= '0'
    mulu a, y, a, 10
    add a, a, c              #   a = 10*a + c
    jmp _read_loop_start     # } while (0)
_read_ret:
    ret a

# Write number in register a to stdout, followed by a newline.
# Fortunately, a 64-bit number has at most 20 digits, and we have 25 registers.
# So we can keep them in registers instead of pushing them onto the stack or heap,
# avoiding the fairly expensive read back.
write:
    divu a, b, a, 10
    jz _write_b, a
    divu a, c, a, 10
    jz _write_c, a
    divu a, d, a, 10
    jz _write_d, a
    divu a, e, a, 10
    jz _write_e, a
    divu a, f, a, 10
    jz _write_f, a
    divu a, g, a, 10
    jz _write_g, a
    divu a, h, a, 10
    jz _write_h, a
    divu a, i, a, 10
    jz _write_i, a
    divu a, j, a, 10
    jz _write_j, a
    divu a, k, a, 10
    jz _write_k, a
    divu a, l, a, 10
    jz _write_l, a
    divu a, m, a, 10
    jz _write_m, a
    divu a, n, a, 10
    jz _write_n, a
    divu a, o, a, 10
    jz _write_o, a
    divu a, p, a, 10
    jz _write_p, a
    divu a, q, a, 10
    jz _write_q, a
    divu a, r, a, 10
    jz _write_r, a
    divu a, s, a, 10
    jz _write_s, a
    divu a, t, a, 10
    jz _write_t, a
    add a, a, ord('0')
    sw 0xffffffffffffffff, a
_write_t:
    add t, t, ord('0')
    sw 0xffffffffffffffff, t
_write_s:
    add s, s, ord('0')
    sw 0xffffffffffffffff, s
_write_r:
    add r, r, ord('0')
    sw 0xffffffffffffffff, r
_write_q:
    add q, q, ord('0')
    sw 0xffffffffffffffff, q
_write_p:
    add p, p, ord('0')
    sw 0xffffffffffffffff, p
_write_o:
    add o, o, ord('0')
    sw 0xffffffffffffffff, o
_write_n:
    add n, n, ord('0')
    sw 0xffffffffffffffff, n
_write_m:
    add m, m, ord('0')
    sw 0xffffffffffffffff, m
_write_l:
    add l, l, ord('0')
    sw 0xffffffffffffffff, l
_write_k:
    add k, k, ord('0')
    sw 0xffffffffffffffff, k
_write_j:
    add j, j, ord('0')
    sw 0xffffffffffffffff, j
_write_i:
    add i, i, ord('0')
    sw 0xffffffffffffffff, i
_write_h:
    add h, h, ord('0')
    sw 0xffffffffffffffff, h
_write_g:
    add g, g, ord('0')
    sw 0xffffffffffffffff, g
_write_f:
    add f, f, ord('0')
    sw 0xffffffffffffffff, f
_write_e:
    add e, e, ord('0')
    sw 0xffffffffffffffff, e
_write_d:
    add d, d, ord('0')
    sw 0xffffffffffffffff, d
_write_c:
    add c, c, ord('0')
    sw 0xffffffffffffffff, c
_write_b:
    add b, b, ord('0')
    sw 0xffffffffffffffff, b
    sw 0xffffffffffffffff, ord('\n')
    ret
# End of write.

Full output from my timing loop, in case anyone wants to check the results and/or my copy-paste and math.
13
23
31
37
41
47
47
59
61
79
Execution terminated after 1148 cycles with exit code 0.
/usr/local/bin/golf.py factor.bin <<< $num  0.09s user 0.02s system 94% cpu 0.115 total
2
2
2
2
3
3
107
1121707
164546579
Execution terminated after 9535194 cycles with exit code 0.
/usr/local/bin/golf.py factor.bin <<< $num  55.03s user 0.07s system 99% cpu 55.136 total
3
3
3
7
7
7
13
50759273983933
Execution terminated after 60559378 cycles with exit code 0.
/usr/local/bin/golf.py factor.bin <<< $num  351.38s user 0.32s system 99% cpu 5:51.89 total
7
7
7
13
2531
4091
250250521
Execution terminated after 135135 cycles with exit code 0.
/usr/local/bin/golf.py factor.bin <<< $num  0.84s user 0.01s system 99% cpu 0.857 total
31
89
97
3881
18211
357653
Execution terminated after 155407 cycles with exit code 0.
/usr/local/bin/golf.py factor.bin <<< $num  0.98s user 0.01s system 99% cpu 0.997 total
2
2
2
3
702924188994286579
Execution terminated after 7126449414 cycles with exit code 0.
/usr/local/bin/golf.py factor.bin <<< $num  43067.49s user 86.38s system 99% cpu 12:04:12.58 total
7
103
727
7209485975851
Execution terminated after 22823483 cycles with exit code 0.
/usr/local/bin/golf.py factor.bin <<< $num  134.60s user 0.13s system 99% cpu 2:14.83 total
66449
1604167
1920043
Execution terminated after 13635943 cycles with exit code 0.
/usr/local/bin/golf.py factor.bin <<< $num  81.02s user 0.06s system 99% cpu 1:21.12 total
322255481
52528036667
Execution terminated after 2739172134 cycles with exit code 0.
/usr/local/bin/golf.py factor.bin <<< $num  16119.02s user 12.31s system 99% cpu 4:29:03.61 total
9929766466606501253
Execution terminated after 26784802677 cycles with exit code 0.
/usr/local/bin/golf.py factor.bin <<< $num  156158.25s user 186.81s system 49% cpu 88:35:03.65 total

I tried a C# program using this same basic algorithm. Same numbers, runtime < 2min. How slow is Golf?

@edc65 Quite slow. I actually wrote a c version first to go off of, it did the largest one in under 30 seconds, the largest completed by golf so far in 7.5.

Also, you'll note that 1 GHz is a billion cycles per second, so at full processor speed (2-3GHz) the 10B cycles measured so far would have completed in more like 3-5 seconds instead of 16 hours.

@Kevin take a look at the examples in the github repository - I updated the number input/output to use the callstack, which is only 1 cycle/digit overhead over your hardcoded version :) Also, if you want real speed you can use this to remove the divu: http://stackoverflow.com/questions/5558492/divide-by-10-using-bit-shifts . As for your answer - this question was not intended to be solved using trial division :P

You can speed up your algorithm a lot by checking if factor * factor < number - no number can have factors greater than the square root.

@orlp I'll need the division result anyway unless the condition is false, so that'd be 3 extra ops per iteration to save 7 on the last. I'll check out the links when I have a chance.

And I know you were going for something faster, but, well, it's an answer and at least establishes a baseline for faster algorithms to aim for.  I was looking at wheel factorization last night, so I'll see about upgrading soon.

@Kevin Don't waste your time on wheel factorization. It only gives a linear speedup over trial factorization.

Well, I'll take another look at field sieves then, see if I can find an explanation that helps me at least understand enough to implement it in C.

@Kevin Field sieves are rather complicated, I would suggest Pollard-Brent or SQUFOF.

score = 378,867,816 cycles
[randomized - your results may vary]
Uses the Miller-Rabin primality test (a deterministic version that can handle up to 2^64), a bit of trial factoring, and ECM factoring.  All the algebraic operations are in there, including modular addition, subtraction, multiplication, exponentiation, and inversion (mod n<2^64).
Modular multiplication is suboptimal - it does a binary search for the quotient.  Computing the remainder of a 128 by 64 divide is tough without a matching builtin instruction.  Speed that up and the whole thing will go faster.
2290 bytes compiled
    step = i
    test = j
    tmp  = k

# prints factors of number on stdin, one per line in arbitrary order, to stdout
main:
    call    read_int
    mov a, x
two:
    # remove factors of 2
    and tmp, a, 1
    jnz odd, tmp
    mov x, 2
    call    write_int
    sw  -1, ord('\n')
    shr a, a, 1
    jmp two
odd:
    cmp tmp, a, 1
    jnz done2, tmp
    call    factorodd
done2:
    halt    0

# a = input value >= 3 and odd.  Prints factors of a and returns.
factorodd:
    call    isprime
    jnz prime2, b
    # n is composite.  Try to find a (not necessarily prime) factor.
    call    trial
    jnz split, b
    call    primepower
    jnz split, b
    call    ecm
split:
    # recurse on two parts
    mov a, b
    call    factorodd
    mov a, c
    jmp factorodd
prime2:
    mov x, a
    call    write_int
    sw  -1, ord('\n')
    ret

# a = input value >= 3 and odd.
# b, c = output values, a = b*c, b,c > 1.
# returns b=0 if failure.
trial:
    mov b, 3
loop5:
    divu    c, r, a, b
    jz  found, r
    add b, b, 2
    leu tmp, b, 1001        # TODO: tune max size
    jnz loop5, tmp
    mov b, 0
found:
    ret b, c

# a = input value >= 3.  Must be odd and have >=2 distinct prime factors.
# b, c = output values, a = b*c, b,c > 1.
ecm:
    mov n, a
loop12:
    # choose a random elliptic curve by picking m with 0 <= m < n
    # y^2 = x^3 + mx + 1
    rand    a
    mov b, 1
    mov c, n
    call    mulmod
    mov m, d
    # check that the descriminant is nonzero.  D = 4m^3+27
    mov a, m
    mov b, m
    call    mulmod
    mov a, d
    call    mulmod
    mov a, d
    mov b, 4
    call    mulmod
    mov a, d
    mov b, 27
    call    addmod
    jz  loop12, d
    # try to find factor of n with this elliptic curve
    call    ecmtry
    jz  loop12, b
    divu    c, tmp, n, b
    ret b, c

# n = modulus
# m = curve param
# b = return value - 0 or a factor of n
ecmtry:
    mov p, 0
    mov q, 1

    # multiply by 2
    mov e, p
    mov f, q
    mov g, p
    mov h, q
    call    ellipticadd
    jnz foundfactor2, d
    mov p, b
    mov q, c

    # continue multiplying by odd numbers
    # TODO: just multiply by odd primes
    mov i, 3
loop15:
    mov e, p
    mov f, q
    mov g, i
    call    ellipticmul
    jnz foundfactor3, d
    mov p, b
    mov q, c
    add i, i, 2
    jnz loop15, p
    jnz loop15, q
    mov b, 0
    ret b
foundfactor3:
    mov b, d
    ret b

# multiplication by a constant in the elliptic curve "group"
#   m = input curve parameter
#   n = input modulus
# e,f = input x,y of point
#   g = input multiplier
# b,c = output x,y of sum
#   d = output 0 if successful, factor of n if not.
ellipticmul:
    # compute g*(e,f) by repeated doubling
    mov x, e
    mov y, f
    mov t, g
    mov r, 0
    mov s, 0
loop14:
    jz  done6, t
    and tmp, t, 1
    jz  noadd, tmp
    # r += x
    mov e, r
    mov f, s
    mov g, x
    mov h, y
    call    ellipticadd
    jnz foundfactor2, d
    mov r, b
    mov s, c
noadd:
    # x += x
    mov e, x
    mov f, y
    mov g, x
    mov h, y
    call    ellipticadd
    jnz foundfactor2, d
    mov x, b
    mov y, c

    shr t, t, 1
    jmp loop14
done6:
    mov b, r
    mov c, s
    mov d, 0
    ret b, c, d
foundfactor2:
    ret d

# addition in the elliptic curve "group"
#   m = input curve parameter
#   n = input modulus
# e,f = input x,y of first point (p)
# g,h = input x,y of second point (q)
# b,c = output x,y of sum
#   d = output 0 if successful, factor of n if not.
ellipticadd:
    px = e
    py = f
    qx = g
    qy = h
    rx = b
    ry = c
    gcd = d
    # 0+q=q
    or  tmp, px, py
    jz  retq, tmp

    # p+0=p
    or  tmp, qx, qy
    jz  retp, tmp

    cmp tmp, px, qx
    jz  diffx, tmp
    cmp tmp, py, qy
    jz  inf, tmp    # px == qx, py != qy, return inf
    jz  inf, py     # px == qx, py == qy, py==0, return inf

    # px == qx, py == qy, py != 0.  This is the double-root case

    # u = numerator = 3 px^2 + a
    mov a, px
    mov b, px
    mov c, n
    call    mulmod
    mov a, d
    mov b, 3
    call    mulmod
    mov a, d
    mov b, m
    call    addmod
    mov u, d

    # v = denominator = 2y
    mov a, py
    mov b, py
    call    addmod
    mov v, d
    jmp divide

diffx:
    # px != qx
    mov a, py
    mov b, qy
    call    submod
    mov u, d        # u = numerator = py - qy

    mov a, px
    mov b, qx
    call    submod
    mov v, d        # v = denominator = px - qx

divide:
    mov a, v
    call    inv
    cmp tmp, c, 1   # gcd(v,n)==1?
    jz  foundfactor, tmp
    mov v, d

    # compute s = u/v mod n = u * v^-1 mod n
    mov a, u
    mov b, v
    mov c, n
    call    mulmod
    mov s, d

    # compute x = s*s - px - qx
    mov a, s
    mov b, s
    call    mulmod
    mov a, d
    mov b, px
    call    submod
    mov a, d
    mov b, qx
    call    submod
    mov x, d

    # compute y = s * (px - x) - py
    mov a, px
    mov b, x
    call    submod
    mov a, d
    mov b, s
    call    mulmod
    mov a, d
    mov b, py
    call    submod

    # return [s*s-px-qx, s*(px-x)-py]
    mov rx, x
    mov ry, d
    mov gcd, 0
    ret rx, ry, gcd

retp:
    mov rx, px
    mov ry, py
    mov gcd, 0
    ret rx, ry, gcd
retq:
    mov rx, qx
    mov ry, qy
    mov gcd, 0
    ret rx, ry, gcd
inf:
    mov rx, 0
    mov ry, 0
    mov gcd, 0
    ret rx, ry, gcd
foundfactor:
    mov gcd, c
    ret gcd

# a = input value >= 3.  Must be odd.
# b = output factor of a.
# if a is a prime power, returns a factor of a.
# otherwise, returns 0.
primepower:
    mov e, 2
loop6:
    mov b, e
    call    nthroot
    leu tmp, c, 3
    jnz notprimepower, tmp

    # compute c^e
    mov r, 1
    mov b, e
loop9:
    mulu    r, tmp, r, c
    dec b
    jnz loop9, b

    cmp tmp, r, a
    jnz isprimepower, tmp

    inc e
    cmp tmp, e, 41  # largest odd power in 2^64 is 3^40
    jz  loop6, tmp
    ret

isprimepower:
    mov b, c
    ret

notprimepower:
    mov b, 0
    ret b

# a = input value
# b = input exponent
# c = output floor(a**(1/b))
nthroot:
    # binary search for the root
    mov c, 0
    mov step, 0x80000000

loop7:
    jz  done3, step
    add test, c, step
    shr step, step, 1

    # check if test^b > a
    # test^b might overflow, so we can't just compute that and compare.
    # so we start with e=a, divide by test b times, and check that
    # the result is 0.
    mov d, b
    mov e, a
loop8:
    divu    e, tmp, e, test
    dec d
    jnz loop8, d

    jz  loop7, e    # test is too big, don't change c

    mov c, test     # test is <= floor(a**(1/b)).  Keep it.
    jmp loop7

done3:
    ret c

# a = input number >= 2
# b = ouput 1/0 if a is prime/composite
isprime:
    # small primes (tests below require that we check these first)
    cmp tmp, a, 2
    jnz prime, tmp
    cmp tmp, a, 3
    jnz prime, tmp
    cmp tmp, a, 5
    jnz prime, tmp
    cmp tmp, a, 7
    jnz prime, tmp
    cmp tmp, a, 11
    jnz prime, tmp
    cmp tmp, a, 13
    jnz prime, tmp
    cmp tmp, a, 17
    jnz prime, tmp
    cmp tmp, a, 19
    jnz prime, tmp
    cmp tmp, a, 23
    jnz prime, tmp
    cmp tmp, a, 29
    jnz prime, tmp
    cmp tmp, a, 31
    jnz prime, tmp
    cmp tmp, a, 37
    jnz prime, tmp

    # even numbers
    and tmp, a, 1
    jz  composite, tmp

    # uses Miller-Rabin with enough fixed bases to guarantee the
    # correct result for numbers up to 2^64.
    # see http://oeis.org/A014233
    mov b, 2
    call    miller_rabin
    jz  composite, c
    mov b, 3
    call    miller_rabin
    jz  composite, c
    mov b, 5
    call    miller_rabin
    jz  composite, c
    mov b, 7
    call    miller_rabin
    jz  composite, c
    mov b, 11
    call    miller_rabin
    jz  composite, c
    mov b, 13
    call    miller_rabin
    jz  composite, c
    mov b, 17
    call    miller_rabin
    jz  composite, c
    mov b, 19
    call    miller_rabin
    jz  composite, c
    mov b, 23
    call    miller_rabin
    jz  composite, c
    mov b, 29
    call    miller_rabin
    jz  composite, c
    mov b, 31
    call    miller_rabin
    jz  composite, c
    mov b, 37
    call    miller_rabin
    jz  composite, c
prime:
    mov b, 1
    ret b
composite:
    mov b, 0
    ret b

# a = input number >= 3
# b = input base value (1 < b < a-1)
# c = output 1 = may be prime, 0 = definitely composite
miller_rabin:
    mov p, a
    mov t, b

    sub q, p, 1
    mov s, 0
    sub e, a, 1
loop2:
    and tmp, e, 1
    jnz endloop2, tmp
    add s, s, 1
    shr e, e, 1
    jmp loop2
endloop2:
    mov a, t
    mov b, e
    mov c, p
    call    pow
    cmp tmp, d, 1
    jnz unknown, tmp
    cmp tmp, d, q
    jnz unknown, tmp
    mov x, d

loop4:
    sub s, s, 1
    jz  composite2, s
    mov a, x
    mov b, x
    mov c, p
    call    mulmod
    cmp tmp, d, 1
    jnz composite2, tmp
    cmp tmp, d, q
    jnz unknown, tmp
    mov x, d
    jmp loop4

composite2:
    mov c, 0
    ret c
unknown:
    mov c, 1
    ret c

# a = input value
# n = input modulus
# returns c, d such that
# c = gcd(a,n)
# d * a % n == gcd(a,n)
inv:
    # extended euclidean algorithm, from
    # http://stackoverflow.com/a/14093613/180090
    new = e
    old = f
    pos = g

    mov p, n
    mov new, 1
    mov old, 0
    mov q, p
    mov pos, 0
loop13:
    jz  done5, a
    divu    q, r, q, a
    mulu    h, tmp, q, new
    add h, old, h
    mov old, new
    mov new, h
    mov q, a
    mov a, r
    xor pos, pos, 1
    jmp loop13
done5:
    mov c, q
    jnz positer, pos
    sub old, p, old
positer:
    mov d, old
    ret c, d

# d = a ** b % c
pow:
    mov r, 1
    mov e, b
    mov t, a
    # t ** e % c
loop3:
    jz  endloop3, e
    and tmp, e, 1
    jz  lowbitclear, tmp

    mov a, t
    mov b, r
    call    mulmod  # r = t*r mod c
    mov r, d

lowbitclear:
    shr e, e, 1
    mov a, t
    mov b, t
    call    mulmod  # t = t*t mod c
    mov t, d
    jmp loop3

endloop3:
    mov d, r
    ret d

# d = a * b % c
mulmod:
    # do multiply
    mulu    e, f, a, b

    # binary search for quotient
    mov  q, 0
    mov  step, 0x8000000000000000
loop:
    jz  done, step

    # test = q + step
    add test, q, step
    shr step, step, 1

    # check test*c
    mulu    g, h, test, c
    geu tmp, h, f
    jnz loop, tmp
    leu tmp, h, f
    jnz ok, tmp
    geu tmp, g, e
    jnz loop, tmp
ok:
    # test*c <= a*b.  Use test as the new q.
    mov q, test
    jmp loop

done:
    # q == quotient of (a*b)/c
    mulu    g, h, q, c  # q*c, g+h<<64 should be close to e+f<<64
    sub d, e, g    # remainder
    ret d

# d = (a + b) % n
# requires 0 <= a, b < n
addmod:
    add d, a, b
    leu tmp, d, a   # wrapped 2^64
    jnz overflow, tmp
    leu tmp, d, n   # result less than modulus?
    jnz inrange, tmp
overflow:
    sub d, d, n
inrange:
    ret d

# d = (a - b) % n
# requires 0 <= a, b < n
submod:
    sub d, a, b
    leu tmp, a, b   # below 0?
    jz  nounderflow, tmp
    add d, d, n
nounderflow:
    ret d

read_int:
    mov x, 0
read_int_loop:
    lw c, -1
    cmp q, c, ord("\n")
    jnz read_int_done, q
    sub c, c, ord("0")
    mulu x, d, x, 10
    add x, x, c
    jmp read_int_loop
read_int_done:
    ret x

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

Output:
13
23
31
37
41
47
47
59
61
79
Execution terminated after 799601 cycles with exit code 0.
2
2
2
2
3
3
107
164546579
1121707
Execution terminated after 216769549 cycles with exit code 0.
3
3
3
7
7
7
13
50759273983933
Execution terminated after 939985 cycles with exit code 0.
7
7
7
13
2531
4091
250250521
Execution terminated after 34213849 cycles with exit code 0.
31
89
97
18211
3881
357653
Execution terminated after 9662357 cycles with exit code 0.
2
2
2
3
702924188994286579
Execution terminated after 748732 cycles with exit code 0.
7
103
727
7209485975851
Execution terminated after 912672 cycles with exit code 0.
66449
1920043
1604167
Execution terminated after 38514477 cycles with exit code 0.
322255481
52528036667
Execution terminated after 75568529 cycles with exit code 0.
9929766466606501253
Execution terminated after 738065 cycles with exit code 0.

You use way more Miller-Rabin bases than needed. You can check the size of the integer and then use one of the sets of bases found here: https://miller-rabin.appspot.com/ .