text:
Turtle Graphics Program
Most of you have probably heard of the famous Turtle Graphics program, initially made popular by Logo.  This challenge is to implement a Turtle Graphics program in your language of choice.
Rules:

Rule one is that when the pen is in the down state, it must draw in both the square the turtle leaves and the square the turtle enters.  This is what would happen in real life, so that is what your program should do.
Rule two is the turtle must include these 10 commands, which can be represented in the input as you like:

RESET - resets board to blank - turtle position is default.
UP and DOWN - these two commands set the pen/eraser state.
RIGHT and LEFT - these two commands turn the turtle in the specified direction.
FORWARD - advances turtle to next square.
DRAW and ERASE - these commands set the turtle to drawing and erasing, respectively.
DISPLAY - displays board.
POSITION - prints turtle's x/y coordinate on the board.
STOP, which stops drawing, displays the board, and terminates the program after the user enters any input.

The floor must be 20x20.  You can use vectors, arrays, or anything you like to represent it.
You must stop the turtle and display an error message if the turtle hits the wall.
Default turtle position is 0,0 facing right.

Scoring:
This program will use standard atomic-code-golf scoring rules with a few modifications to try to allow industry programming languages, such as Java and C++, to compete.

Imports, includes, usings and other similar statements do not score anything.
Loop header statements each only score one point.  All other statements add the full number of characters in the statement to the score.

Example:
These statements do not score:
#include <iostream>
import java.util.Scanner;

def inputCommand():
string inputCommand(){}

These statements score only one point:
for(int i = 0; i < 9; i++){}
for i in range(0,10):
while(true){}
while x in y:

These statements score the full number of their characters:
string n;
i = 9;

switch(d) {
  case i:
    break;
  default:
    break;
}

return x;

cout<<'example';
cin>>s;
System.out.println()
print('example')

If you have any questions or comments, please let me know in the comments.

Any particular starting position/direction after reset? Also, what should happen if you run out of bounds? Right/left 90 degrees or 45 degrees?

Given how complex this program will need to be, your odd scoring rules will make this overly difficult for people to calculate their score.

how many bonus points would we get for writing a scoring program to score the programs we write for this problem?

rather than all the scoring rules, why not tag it [tag:atomic-code-golf] (and maybe add a few extra rules)?

Or you could just tag it [tag:popularity-contest] and hope for the best.

@JoachimIsaksson Added more rules.  Diagonal is optional - not required.

@serakfalcon Your program can count as a tie with the shortest answer if your scoring program accommodates at least 80% of the languages that answers are posted in.

@Quincunx That sounds like a good idea.

@LegoStormtroopr Are these rules a little more manageable?  The imports, includes, and usings are all together at the beginning of the file, so it will be easy to skip them.

Any rules as to input? As a file? or as individual commands via stdin?

One-character hello world in C with these rules: #include <stdio.h> main(){for(printf("Hello world!\n");0;)6;}

@user2509848 how much is 80% of 1?

@Quirliom I used stdin for mine, but a file is just fine too.

@JanDvorak Round to the nearest whole number - so .8 is rounded to 1.

related. but of course, this is very different. But I'm mentioning this to advertise my question on the linked list. :)

JavaScript, one point
for (s='                    ',
    reset=function(){a=s.split(/./).map(function(){return s.split(/(?=.)/)}); x=0; y=0; dx=1; dy=0; pen='#'; down=1;},
    display=function(){console.log(a.map(function(x){return x.join('')}).join('\n'))},
    position=function(){console.log(x, y)},
    draw=function(){a[y][x]=down?pen:a[y][x]},
    forward=function(){draw(); x+=dx; y+=dy; (y<0||y>19||x<0||x>19) && (console.log('Hit wall')||(dx?(x-=dx):(y-=dy))); draw();},
    turn=function(d){nx=-1*(!dx)*d*dy; dy=(!dy)*d*dx; dx=nx;},
    reset();
    ((p=prompt()) != 'STOP') || display();
    (p == "RESET") && reset(),
    (p == "DISPLAY") && display(),
    (p == "POSITION") && position(),
    (p == "DRAW") && (pen='#'),
    (p == "ERASE") && (pen=' '),
    (p == "UP") && (down=0),
    (p == "DOWN") && (down=1),
    (p == "RIGHT") && turn(1),
    (p == "LEFT") && turn(-1),
    (p == "FORWARD") && forward()
);

Sorry, I couldn't resist.

Mathematica (1 point and 211 208 205 characters)
A:=Abort[]
q@1:=Check[a〚##〛=c,A]&@@p
DI:=Print@ArrayPlot@a
ST:=DI+A
PO:=Print@p
FO:=p+=v
LE:=v=Cross@v
RI:=v=-LE
DR:=c=1
ER:=c=0
UP:=d=0
DO:=d=1
v={UP,DR};
a=0Array[p=0v+1,20p];
Symbol@StringTake[#,2]q@d&/@StringSplit@s

It prints

for
s = "DOWN RIGHT FORWARD FORWARD FORWARD FORWARD LEFT UP FORWARD LEFT \
   FORWARD FORWARD DOWN RIGHT FORWARD UP FORWARD LEFT FORWARD DOWN \
   FORWARD LEFT FORWARD FORWARD UP LEFT LEFT FORWARD FORWARD DOWN ERASE STOP";

I assume that the initial state is up&drawing.
You can put the whole code inside the header of Do loop
`Do[,{code; 1}]`

It is only 1 point!

Python 2.7 (443? Points, 531 chars)

Not really that well golfed and the display looks kind of horrid. Takes input from a file 'i' and runs printing out the output. I defined two new 'commands': 'CW' and 'CCW' which rotate the turtle 90 degrees clockwise and counter-clockwise respectivly.
b=[];u=1;s=r=0;p=[];d=[(1,0),(0,1),(-1,0),(0,-1)];l='0';
def q():
 for i in b:print ''.join(i)
def z():
 r=0;p=[0]*2
 for i in [0]*20:
  b.append([l]*20)
def k():
 b[p[1]][p[0]]=(('1',l)[s],b[p[1]][p[0]])[u]
z()
for c in open('i','r').read().split():
 if c=="RESET":z()
 elif c=="UP":u=1
 elif c=="DOWN":u=0
 elif c=="FORWARD":
  k();p[0]+=d[r][0];p[1]+=d[r][1];k()
 elif c=="DRAW":s=0
 elif c=="ERASE":s=1
 elif c=="DISPLAY":q()
 elif c=="POSITION":print p
 elif c=="STOP":q();break
 elif c=="CW":r=(r+1)%4
 elif c=="CCW":r=(r-1)%4

Test Input:
DOWN FORWARD FORWARD CW FORWARD FORWARD CW FORWARD FORWARD CW FORWARD FORWARD CW UP FORWARD FORWARD FORWARD FORWARD DOWN FORWARD FORWARD CW FORWARD FORWARD CW FORWARD FORWARD CW FORWARD FORWARD CW ERASE FORWARD FORWARD STOP

Output:
11100000000000000000
10101010000000000000
11101110000000000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000

I found 431 characters - you have three for-loops in there, did you forget to remove one?

Quite Possibly, let me recalculate.

Java
Here is my program - un-golfed (too complicated), unscored (I am unsure what the enums and Scanner object creation score as), and over-done:
package javaapplication74;

import java.util.Scanner;
import static java.lang.Integer.parseInt;

public class JavaApplication74 {

// create Scanner for input
static Scanner in = new Scanner(System.in);

// enumerator of commands
private enum Commands {RESET, UP, DOWN, RIGHT, LEFT, FORWARD, DISPLAY, ERASE, REVERSE, POSITION, STOP, ERROR};

// enumerator of directions turtle can face
private enum Direction {UP, DOWN, RIGHT, LEFT};

// array of valid commands
static final char[] commands = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'r' };

// width and height of room;
static final int ROOM = 20;

// turtle's position
static int[] position = {0, 0};

// number of squares to move
static int move = 0;

// Write a "turtle graphics" program
public static void main(String[] args)
{
    // array of drawn lines
    boolean[][] floor = new boolean[ROOM][ROOM];

    // store command
    Commands command;

    // store current direction - default right
    Direction direction = Direction.RIGHT;

    // pen in drawing condition
    boolean draw = false;
    boolean erase = false;

    // provide directions
    directions();

    // get and execute commands until stop
    do {
        // get command
        command = inputCommand();

        // analyse and execute command
        switch(command) {
            case RESET:
                reset(floor);
            case UP:
                draw = false;
                erase = false;
                break;
            case DOWN:
                draw = true;
                erase = false;
                break;
            case RIGHT:
            case LEFT:
                direction = turn(command, direction);
                break;
            case FORWARD:
                floor = move(floor, direction, draw, erase);
                break;
            case DISPLAY:
                display(draw, floor);
                break;
            case ERASE:
                draw = false;
                erase = true;
                break;
            case REVERSE:
                reverse(floor);
                break;
            case POSITION:
                showPosition(direction);
                break;
            case STOP:
            case ERROR:
                break;

        }   // end switch

    } while(command != Commands.STOP);
    // end do-while
}   // end method main

// Provide directions
public static void directions()
{
    System.out.println("This is a turtle graphics program.");
    System.out.println("You have 11 commands available, use the number to the right to use that command:");
    System.out.printf("%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n", "0: Clear floor.", "1: Pen up, eraser up (default position).", "2: Pen down.", "3: Turn right.", "4: Turn left.",
            "5: Go forward x spaces (enter 5,x)", "6: Display current layout", "7: Erase", "8: Show turtle's position", "9: Quit program", "r: Draw or erase current square.");
    System.out.println("Note: the turtle will draw one more symbol than the number of spaces entered\n\tbecause it will draw in the square it is initially in.");

}   // end method main

// Input command
public static Commands inputCommand()
{
    // store command as string
    String command;

    // input command
    do {
        System.out.print("Enter your command: ");
        command = in.next();

    } while(!valid(command.charAt(0)));
    // end do-while

    // return command as enum value
    switch(command.charAt(0)) {
        case '0':
            return Commands.RESET;
        case '1':
            return Commands.UP;
        case '2':
            return Commands.DOWN;
        case '3':
            return Commands.RIGHT;
        case '4':
            return Commands.LEFT;
        case '5':

            // recover from bad input
            if(command.substring(1).isEmpty() || command.charAt(1) != ',' || command.substring(2).isEmpty())
                return Commands.ERROR;

            move = parseInt(command.substring(2));
            return Commands.FORWARD;
        case '6':
            return Commands.DISPLAY;
        case '7':
            return Commands.ERASE;
        case '8':
            return Commands.POSITION;
        case '9':
            return Commands.STOP;
        case 'r':
            return Commands.REVERSE;
        default:
            return Commands.ERROR;
    }   // end switch
}   // end method inputCommand

// Validate command
public static boolean valid(char c)
{
    for(int ch : commands) {
        if(c == ch)
            return true;

    }   // end for

    // if reach this point, not valid
    return false;

}   // end method valid

// Turn turtle
public static Direction turn(Commands c, Direction d)
{
    // turn turtle
    switch(d) {
        case UP:
            if(c == Commands.RIGHT)
                d = Direction.RIGHT;
            else
                d = Direction.LEFT;

            break;

        case RIGHT:
            if(c == Commands.RIGHT)
                d = Direction.DOWN;
            else
                d = Direction.UP;

            break;

        case DOWN:
            if(c == Commands.RIGHT)
                d = Direction.LEFT;
            else
                d = Direction.RIGHT;

            break;

        case LEFT:
            if(c == Commands.RIGHT)
                d = Direction.UP;
            else
                d = Direction.DOWN;

            break;

    }   // end switch

    return d;

}   // end method turn

// move turtle
public static boolean[][] move(boolean[][] floor, Direction d, boolean draw, boolean erase)
{
    // get direction to move turtle
    switch(d) {
        // move turtle up
        case UP:
            for(; move > 0; move--) {

                // draw, erase, or leave square
                draw(draw, erase, floor);

                // change position
                position[0]--;

                // return to caller if turtle hits wall
                if(position[0] <= 0) {

                    // reset value
                    position[0] = 0;

                    // print warning
                    System.out.println("Your turtle hit the wall and had to stop.");

                    // stop moving turtle
                    break;

                }   // end if
            }   // end for

            break;

        // move turtle down
        case DOWN:
            for(; move > 0; move--) {

                // draw, erase, or leave square
                draw(draw, erase, floor);

                // change position
                position[0]++;

                // make sure turtle does not walk through wall
                if(position[0] >= ROOM) {

                    // reset value
                    position[0] = ROOM-1;

                    // print warning
                    System.out.println("Your turtle hit the wall and had to stop.");

                    // stop moving turtle
                    break;

                }   // end if
            }   // end for

            break;

        // move turtle right
        case RIGHT:
            for(; move > 0; move--) {

                // draw, erase, or leave square
                draw(draw, erase, floor);

                // change position
                position[1]++;

                // make sure turtle does not walk through wall
                if(position[1] >= ROOM) {

                    // reset value
                    position[1] = ROOM-1;

                    // print warning
                    System.out.println("Your turtle hit the wall and had to stop.");

                    // stop moving turtle
                    break;

                }   // end if
            }   // end for

            break;

        // move turtle left
        case LEFT:
            for(; move > 0; move--) {

                // draw, erase, or leave square
                draw(draw, erase, floor);

                // change position
                position[1]--;

                // make sure turtle does not walk through wall
                if(position[1] <= 0) {

                    // reset value
                    position[1] = 0;

                    // print warning
                    System.out.println("Your turtle hit the wall and had to stop.");

                    // stop moving turtle
                    break;

                }   // end if
            }   // end for

            break;

    }   // end switch

    // draw, erase, or leave square
    draw(draw, erase, floor);

    return floor;

}   // end method move

// Draw, erase, or leave square
public static boolean[][] draw(boolean draw, boolean erase, boolean[][] floor)
{
    // if draw, turtle cannot leave square without drawing
    if(draw)
        floor[position[0]][position[1]] = true;

    // if erase, turtle cannot leave square without erasing
    if(erase)
        floor[position[0]][position[1]] = false;

    return floor;

}   // end method draw

// Display array
public static void display(boolean draw, boolean[][] array)
{
    // loop through array
    for(boolean b[] : array) {
        for(boolean bb : b) {

            // draw picture
            if(bb)
                System.out.print("*");
            else
                System.out.print(" ");

        }   // end inner for

        // return at end of row
        System.out.println();

    }   // end outer for
}   // end method display

// Reverse value (draw or erase square) of current position
public static void reverse(boolean floor[][])
{
    floor[position[0]][position[1]] = !floor[position[0]][position[1]];

}   // end method reverse

// Show turtle's position
public static void showPosition(Direction d)
{
    // x-y coordinate
    System.out.printf("(%d, %d)\n", position[1], position[0]);

    // direction
    System.out.print("You are facing ");
    switch(d) {
        case UP:
            System.out.println("up.");
            break;
        case DOWN:
            System.out.println("down.");
            break;
        case RIGHT:
            System.out.println("right.");
            break;
        case LEFT:
            System.out.println("left.");
            break;

    }   // end switch

}   // end method showPosition
// Reset floor to blank
public static boolean[][] reset(boolean[][] floor)
{
    for(boolean b[] : floor)
        for(int i = 0; i < b.length; i++)
            b[i] = false;

    return floor;

}   // end method reset
}   // end class JavaApplication74

I wrote this for my programming class about a month ago, so it isn't optimized for golf. I thought you might like to see my solution though.

You submitted an answer to your own Gulf challenge, but didn't golf it andcouldn't score it. What does that day about your rules?

@LegoStormtroopr I didn't score it because I wasn't sure about the atomic-golf rules.  My rules were modified to only not score imports and score loop statements at only 1 point - that isn't that hard, is it?  I made a comment on what I was unsure about in the answer.  I will score it if you will explain what the rules for these are.  Also, golfing the names won't really help because user-defined variables only score 1 point each time thy are used.

What's the course maximum?

If you mean for program score, nothing.  It will be interesting to see what people come up with.

Java, 10 Points
import java.util.Scanner;
import static java.lang.System.*;

class Turtle{
    public static void main(String...args){
        Scanner s=new Scanner(in).useDelimiter("\\W+");
        for(
            String board = "Lol I'm coding stuff".replaceAll(".","00000000000000000000\n"),
                input,
                x = "0",
                y = "0",
                rotation = "0",
                up = "true",
                mode = "1",
                nop
        ;
            null==(s.hasNext()?null:out.printf(board))
        ;
            nop =
            ((input=s.next()).equals("RESET")
                ?(x = y = rotation = "0") + (up = "true") + (mode = "1")
            :input.equals("STOP")
                ?(s=new Scanner("")).toString()
            :input.equals("DISPLAY")
                ?out.printf(board).toString()
            :input.equals("POSITION")
                ?out.printf("(%s,%s)",x,y).toString()
                :"")+
            (up = input.equals("UP")
                ?"true"
            :input.equals("DOWN")
                ?"false"
                :up)+
            (rotation = input.equals("LEFT")
                ?""+((1+Integer.parseInt(rotation))%4)
            :input.equals("RIGHT")
                ?""+((3+Integer.parseInt(rotation))%4)
                :rotation)+
            (mode = input.equals("DRAW")
                ?"1"
            :input.equals("ERASE")
                ?"0"
                :mode)+
            (input.equals("FORWARD")
                ?
                    ((x = Integer.parseInt(rotation)%2!=0
                        ?x
                    :rotation.equals("0")
                        ?Integer.parseInt(x)+1+""
                        :Integer.parseInt(x)-1+"")+
                    (y = Integer.parseInt(rotation)%2==0
                        ?y
                    :rotation.equals("3")
                        ?Integer.parseInt(y)+1+""
                        :Integer.parseInt(y)-1+""))
                :"")+
            (out.printf("\nx:%s y:%s rot:%s up:%s mode:%s input:%s\n",x,y,rotation,up,mode,input))+
            (board = up.equals("false")
                ?board.replaceFirst("(?<=(?:[01]{20}\n){"+y+"}.{"+x+"}).",mode)
                :board)+
            (Integer.parseInt(x)<0||Integer.parseInt(x)>20||Integer.parseInt(y)<0||Integer.parseInt(y)>20
                ?(board = String.format("Error at position (%s,%s)",x,y)) + (s=new Scanner("")).toString()
                :"")
        );
    }
}

Scanner s=new Scanner(in).useDelimiter("\\W+"); counts as 9 points, and the rest of the main method is just a for-loop's header and so it counts as 1 point.

Loop header statements each only score one point

Great job twisting the rules to your advantage!  This is probably the first time Java will win a golf program!

source: Stack Exchange

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

sort: votes


text:
JavaScript load and SHA-256
This is a code golf puzzle with a real-world application. Some current browsers, if you enter a URL that looks like
data:text/html,<script>alert("hi")</script>

will execute the given JavaScript code. Now suppose you had a URL which looked like (pseudocode):
data:text/html,<script>
    myPublicKey="12345678";
    cryptoLib=download("http://example.com/somecryptolib.js");
    if(sha256sum(cryptoLib) == "12345678")
        eval(cryptoLib)
</script>

If you printed this on business cards as a QR code, then anyone who went to that URL with an appropriate browser would get a public-key crypto client, with your public key pre-loaded, without having to install anything. Because of the hash verification, you could be confident they got the real crypto software, even if their ISP meddles with traffic.
Unfortunately, the real version of this pseudocode is quite long for a QR code. My challenge is: how short can you make it? An implementation would:

Be a data:... URL which executes correctly from the address bar of Chrome and Firefox. (To make a valid data: URL, you'll have to encode % as %25, and strip newlines)
Have a URL and a SHA-256 hash embedded, preferably as plain-text string literals near the beginning
Download a file from a URL using XMLHttpRequest (or a similar API). (Note that the server will need to include an Access-Control-Allow-Origin:* header for this to work.)
If that URL loaded successfully and the result is a file with the expected hash, eval() it. Otherwise do nothing or show an error message.
All builtin JavaScript functions that're present in both Chrome and Firefox are fair game, but loading libraries is impossible.
Use as few bytes as possible

I made a naive version using CryptoJS (minified version):
data:text/html,<script>
    u = 'http://localhost:8000'
    h = '5e3f73c606a82d68ef40f9f9405200ce24adfd9a4189c2bc39015345f0ee46d4'
    // Insert CryptoJS here
    r = new XMLHttpRequest;
    r.open('GET', u, false);
    r.send();
    if(CryptoJS.SHA256(r.response) == h)
        eval(r.response);
</script>

Which comes out of the minifier as:
data:text/html,<script>u="http://localhost:8000";h="5e3f73c606a82d68ef40f9f9405200ce24adfd9a4189c2bc39015345f0ee46d4";var CryptoJS=CryptoJS||function(k,w){var f={},x=f.lib={},g=function(){},l=x.Base={extend:function(a){g.prototype=this;var c=new g;a&&c.mixIn(a);c.hasOwnProperty("init")||(c.init=function(){c.$super.init.apply(this,arguments)});c.init.prototype=c;c.$super=this;return c},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var c in a)a.hasOwnProperty(c)&&(this[c]=a[c]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}},t=x.WordArray=l.extend({init:function(a,c){a=this.words=a||[];this.sigBytes=c!=w?c:4*a.length},toString:function(a){return(a||y).stringify(this)},concat:function(a){var c=this.words,d=a.words,b=this.sigBytes;a=a.sigBytes;this.clamp();if(b%254)for(var e=0;e<a;e++)c[b+e>>>2]|=(d[e>>>2]>>>24-8*(e%254)&255)<<24-8*((b+e)%254);else if(65535<d.length)for(e=0;e<a;e+=4)c[b+e>>>2]=d[e>>>2];else c.push.apply(c,d);this.sigBytes+=a;return this},clamp:function(){var a=this.words,c=this.sigBytes;a[c>>>2]&=4294967295<<32-8*(c%254);a.length=k.ceil(c/4)},clone:function(){var a=l.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var c=[],d=0;d<a;d+=4)c.push((1<<30)*4*k.random()|0);return new t.init(c,a)}}),z=f.enc={},y=z.Hex={stringify:function(a){var c=a.words;a=a.sigBytes;for(var d=[],b=0;b<a;b++){var e=c[b>>>2]>>>24-8*(b%254)&255;d.push((e>>>4).toString(16));d.push((e&15).toString(16))}return d.join("")},parse:function(a){for(var c=a.length,d=[],b=0;b<c;b+=2)d[b>>>3]|=parseInt(a.substr(b,2),16)<<24-4*(b%258);return new t.init(d,c/2)}},m=z.Latin1={stringify:function(a){var c=a.words;a=a.sigBytes;for(var d=[],b=0;b<a;b++)d.push(String.fromCharCode(c[b>>>2]>>>24-8*(b%254)&255));return d.join("")},parse:function(a){for(var c=a.length,d=[],b=0;b<c;b++)d[b>>>2]|=(a.charCodeAt(b)&255)<<24-8*(b%254);return new t.init(d,c)}},n=z.Utf8={stringify:function(a){try{return decodeURIComponent(escape(m.stringify(a)))}catch(c){throw Error("Malformed UTF-8 data");}},parse:function(a){return m.parse(unescape(encodeURIComponent(a)))}},B=x.BufferedBlockAlgorithm=l.extend({reset:function(){this._data=new t.init;this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=n.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var c=this._data,d=c.words,b=c.sigBytes,e=this.blockSize,f=b/(4*e),f=a?k.ceil(f):k.max((f|0)-this._minBufferSize,0);a=f*e;b=k.min(4*a,b);if(a){for(var p=0;p<a;p+=e)this._doProcessBlock(d,p);p=d.splice(0,a);c.sigBytes-=b}return new t.init(p,b)},clone:function(){var a=l.clone.call(this);a._data=this._data.clone();return a},_minBufferSize:0});x.Hasher=B.extend({cfg:l.extend(),init:function(a){this.cfg=this.cfg.extend(a);this.reset()},reset:function(){B.reset.call(this);this._doReset()},update:function(a){this._append(a);this._process();return this},finalize:function(a){a&&this._append(a);return this._doFinalize()},blockSize:16,_createHelper:function(a){return function(c,d){return(new a.init(d)).finalize(c)}},_createHmacHelper:function(a){return function(c,d){return(new A.HMAC.init(a,d)).finalize(c)}}});var A=f.algo={};return f}(Math);(function(k){for(var w=CryptoJS,f=w.lib,x=f.WordArray,g=f.Hasher,f=w.algo,l=[],t=[],z=function(a){return (1<<30)*4*(a-(a|0))|0},y=2,m=0;64>m;){var n;a:{n=y;for(var B=k.sqrt(n),A=2;A<=B;A++)if(!(n%25A)){n=!1;break a}n=!0}n&&(8>m&&(l[m]=z(k.pow(y,0.5))),t[m]=z(k.pow(y,1/3)),m++);y++}var a=[],f=f.SHA256=g.extend({_doReset:function(){this._hash=new x.init(l.slice(0))},_doProcessBlock:function(c,d){for(var b=this._hash.words,e=b[0],f=b[1],p=b[2],k=b[3],s=b[4],l=b[5],m=b[6],n=b[7],q=0;64>q;q++){if(16>q)a[q]=c[d+q]|0;else{var v=a[q-15],g=a[q-2];a[q]=((v<<25|v>>>7)^(v<<14|v>>>18)^v>>>3)+a[q-7]+((g<<15|g>>>17)^(g<<13|g>>>19)^g>>>10)+a[q-16]}v=n+((s<<26|s>>>6)^(s<<21|s>>>11)^(s<<7|s>>>25))+(s&l^~s&m)+t[q]+a[q];g=((e<<30|e>>>2)^(e<<19|e>>>13)^(e<<10|e>>>22))+(e&f^e&p^f&p);n=m;m=l;l=s;s=k+v|0;k=p;p=f;f=e;e=v+g|0}b[0]=b[0]+e|0;b[1]=b[1]+f|0;b[2]=b[2]+p|0;b[3]=b[3]+k|0;b[4]=b[4]+s|0;b[5]=b[5]+l|0;b[6]=b[6]+m|0;b[7]=b[7]+n|0},_doFinalize:function(){var a=this._data,d=a.words,b=8*this._nDataBytes,e=8*a.sigBytes;d[e>>>5]|=128<<24-e%2532;d[(e+64>>>9<<4)+14]=k.floor(b/(1<<30)*4);d[(e+64>>>9<<4)+15]=b;a.sigBytes=4*d.length;this._process();return this._hash},clone:function(){var a=g.clone.call(this);a._hash=this._hash.clone();return a}});w.SHA256=g._createHelper(f);w.HmacSHA256=g._createHmacHelper(f)})(Math);r=new XMLHttpRequest;r.open("GET",u,!1);r.send();CryptoJS.SHA256(r.response)==h&&eval(r.response)</script>

Tested with this minimal Python server:
import BaseHTTPServer

class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def do_HEAD(s):
        s.send_response(200)
        s._sendHeaders()
        s.end_headers()
    def do_GET(s):
        s.send_response(200)
        s._sendHeaders()
        s.end_headers()
        s.wfile.write('alert("Success!")')
    def _sendHeaders(s):
        s.send_header("Content-type", "script/javascript");
        s.send_header("Access-Control-Allow-Origin", "*");

def run(server_class=BaseHTTPServer.HTTPServer,
    handler_class=RequestHandler):
    server_address = ('', 8000)
    httpd = server_class(server_address, handler_class)
    httpd.serve_forever()

run()

The JavaScript portion is 4700 bytes, but it can be much smaller. How small can it get?

Interesting question. Sending the crypto library from the server to the client to eval and then making a second request with the crypto library loaded would defeat the point of this correct? I've spent some time working on a solution and ended up doing just that, but then realized that it means trusting the ISP to not mess with the crypto library which is a problem.

Right; to be secure, the first loaded file has to have its hash validated using code that's entirely in the URL. Luckily, this only needs one hash function (which doesn't necessarily have to be SHA-256, though), which was 4700 bytes naively and could probably be <1kb with heavy optimization. (That then handles loading and verifying a larger library, where size doesn't matter so mcuh since it's no longer inside a URL).

"loading libraries is impossible." - shouldn't loading libraries be allowed, except it must be done from code, such as by creating a script element, setting its async property to false and inserting it to the document?

@JanDvorak, but how do you confirm that the library hasn't been modified?

script/javascript? You mean text/javascript.

844 Characters
K=new XMLHttpRequest;K.open("get","http://localhost:8000",O=j=n=q=0);K.send();m=K.response;l=m.length;k=l+1|63;W=[o=Math.pow];for(H=[R=o(i=2,32)];i<313+l;i++)for(W[i]||(K[q]=o(i,1/3)*R|0,H[q++]=o(i,.5)*R|0,I=2);W[i*I++]=199>I;)o[n>>2]|=(n^l?m.charCodeAt(n):128)<<24-n++%4*8;for(o[k>>2]=8*l;j<=k;H[I-7]+=a=t+T|0)i=j++&63||(a=H[0],b=H[1],c=H[2],d=H[3],e=H[4],f=H[5],g=H[6],h=H[7],0),y=W[i-15],x=W[i-2],t=h+(e<<26^e>>>6^e<<21^e>>>11^e<<7^e>>>25)+(e&f^~e&g)+K[i]+(W[i]=16>i?o[O++]:(y<<25^y>>>7^y<<14^y>>>18^y>>>3)+W[i-7]+(x<<15^x>>>17^x<<13^x>>>19^x>>>10)+W[i-16]),T=(a<<30^a>>>2^a<<19^a>>>13^a<<10^a>>>22)+(a&b^a&c^b&c),H[I=i-63|7]+=h=g,H[I-1]+=g=f,H[I-2]+=f=e,H[I-3]+=e=d+t|0,H[I-4]+=d=c,H[I-5]+=c=b,H[I-6]+=b=a;1581216710^H[0]|111684968^H[1]|4014012921^H[2]|1079115982^H[3]|615382426^H[4]|1099547324^H[5]|956388165^H[6]|4042147540^H[7]||eval(m)

The URL and Hash values are hard coded. The Hash is encoded as decimal double words, the values in my code correspond to the script in the example Python server.
I also didn't bother doing the URL encoding, but it works when you type javascript: manually in the URL bar and then paste the code (and also in the console).
The implementation is not compliant, but it should work for files smaller than 512 MB.

HTML Data URL, 131 Characters
It's been a while and there's a native way to do this now: Subresource Integrity. Also, data URLs are not allowed to be linked to by major browsers so this whole idea no longer works :( Also, I used a hosted copy of the script that should be CORS-accessible, http:localhost:8000 was what OP specified and would save 3 characters.
data:text/html,<script src=https:fk.ci/9Rg2HKk.js integrity=sha256Xj9zxgaoLWjvQPn5QFIAziSt/ZpBicK8OQFTRfDuRtQ crossorigin></script>

all_licenses: 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/


text:
How to write a C program for multiplication without using the * and + operators?

Is it possible to write a C program that multiplies two numbers without using the multiplication and addition operators?

I found this on Stack Overflow. Please help this poor programmer with his problem. And please don't give answers like c = a/(1/((float)b)), which is exactly the same as c = a*b. (And is already given as an answer.)
The answer with the most upvotes on January 19th 2014 wins.
Note: This is a code-trolling question. Please do not take the question and/or answers seriously. More information is in code-trolling.

Please be more specific about "numbers".

@PaulR use your fantasy

I guess the original Q meant any numbers...

The given example doesn't work with integers so I'm guessing it may be a floating point task?

Why doesn't it work with ints? (except 0)

1/n is 0 for n > 1 when n is an int.

oh.. yes, you're right... doesn't matter for the question

Code-golf.SE should not be a place for you to mock questions you've seen on StackOverflow.

@Gareth, are you sure?  The first line of this suggests this may be quite appropriate.

@DarrenStone I've enjoyed being a member of this site for a couple of years now and I'm seriously concerned that questions like this are mean and unpleasant. I don't want to see this site become reddit-like.

@Gareth, I certainly didn't intend to be mean with my comment. I wrestle with the spirit and noise that [tag:code-trolling] questions bring, but OP has tagged the question correctly and code-trolling is based on jest and mockery of real questions.

@DarrenStone I think you misunderstood me, I think this type of question which mocks an SO user is a bit mean. Your comment was a reasonable one (as they usually are).

I´m waiting for someone write an algorithm based on sleep

Since all computers are essentially adding machines, with flow control, comparators, and about every other operation including incrementing the program counter dependent on addition then no, in the strictest sense this program can't be written, at least not for any non-analogue computer.

This question isn't as ridiculous as it sounds. Actual computer hardware (transistors) don't have multiply and add operations -- they have basic logic operations like NOT, AND, OR, XOR. Figuring out how to answer this question can give you excellent insight into how a computer really works at the level of logic gates.

@Gabe yeah, but the O(bits^2) solution is inappropriate for a code-trolling challenge :-)

@Gareth - I don't see that the OP is in any way being mean or "mocking" the SO user.

@JanDvorak: Multiplying is O(digits^2). If your computer can do it faster than that, it's because it has O(digits^2) transistors that all operate simultaneously.

last week I had an interview I was asked to multiply a number with 7  without using + and * I answered result = (number << 3) - number.

@GrijeshChauhan: your solution does not work for the full valid range of possible input values (it overflows for part of the range).

@PaulR Yes. You are correct, in-fact it can cause  undefined behavior if left-shit sets sign-bit(msb). But fortunately interviewer was happy :) I guess because he asked question in Puzzle section(not in programming). Btw I now like @ MarkLakata trick.

@GrijeshChauhan: I think you're confused between left shift and right shift of signed values - the only problem with the left shift in your solution is the potential for overflow in the intermediate result - otherwise it's fine.

@GrijeshChauhan: To avoid overflow of the intermediate result, set result = (number<<2) + (number <<1) + number

@PieterGeerkens yup, this kind of technique can be helpful, but you are using +!!

@GrijeshChauhan: Oops! Time for a coffee I think.

Unless you are compiling with -Ofast (which is gcc mode that doesn't calculate accurately, like C standard says), a/(1/((float)b)) is not identical to a*b. This is because floating point math is special, and most optimizations cannot be done.

What about solutions that use a - -b to substitute for a + b?

"c = a * b" doesn't use "the * and + operators", it only uses one of them :p (how do you make 35 cents with two coins, where one of them isn't a quarter?)

No one applied the seemingly obvious properties of natural logarithms? For shame? Oh someone did mention exp(x) though. In (roughly) algebraic form:
ab=exp(log(a)+log(b)) So what to do since we can't use addition? I'll not cheat and assume "direct addition" is the only kind forbidden. You could use a table or slide rule (which is just an analog computer version of the table). You'd be imitating addition, though. Hmm, thinking of another angle of attack... OK, multiplying complex numbers adds the angles. angleof((1@ angle A)(1@ angle B)) = (A+B) mod 2Pi. LOL, going around in circles unless A=

(oops, it hates left-arrows so I replaced it with {) Note that on some level, logic gates are in fact related to addition, comparison, and tables. You can state (2 inputs) XOR as 0{A+B{2 or that the sum is equal to 1. A 3-input NAND gate can be stated as A+B+C=3 and so on. On some level, a (stateless) logic device is just asking "Does the sum of these inputs equal to some value in the following table?" and combining the answers recursively for many groups of inputs into yet more tables. This is in fact the idea behind Programmable Array Logic devices. This is getting into major number theory t

@GrijeshChauhan @PieterGeerkens Regarding result = (number << 3) - number : it does not have an overflow problem. It does overflow, of course, but the result is correct anyway, because (on all normal C machines) both the << and the '-' overflow as in modular arithmetic. So does number*7. So you get the proper result, overflow or not. It's common for C compilers to do such transforms when the shift/add is smaller than the multiply-by-constant.

@greggo so I am pass :)

Code-trolling is in the process of being removed, as per the official stance. This question receieved almost 50% "keep" votes on the poll, and is an outlier in that it has an extreme amount of votes, votes on the answers, and amount of answers, so I am locking it.

Always use recursion
Recusion is the right way!
int inc(int x) {
    return x&1?inc(x>>1)<<1:x|1;
}

int dec(int x) {
    return x&1?x^1:dec(x>>1)<<1|1;
}

int add(int x, int y) {
    return x?add(dec(x),inc(y)):y;
}

int mul(int x, int y) {
    return x?x^1?add(y,mul(dec(x),y)):y:0;
}

int main() {
    int a, b;
    scanf("%i\n%i", &a, &b);
    printf("%i", mul(a,b));
}

I would give +3 if I could: one for the ultimate recursion, one for ??:: without parentheses, one for solving the problem without trying to tweak the rules ;)

The sheer elegance of this has dissuaded me from posting my ripple carry adder based solution.  Bit-wise addition by recursion.  Wow.

Wow. Nice increment operator, more readable than mine :-)

If Picasso was a programmer...

+ can be made of two -s, so add is not necessary (only if you must deal with unsigned integers)

@SargeBorsch But where'd the fun be in that?

Could someone explain one of these functions to a relatively novice programmer? ^^

@HC_ The inc function tests its argument to see if the lowest bit is 1; if so, it calls itself on the remaining upper bits of the argument and returns the result with the same low bit that was checked being set to 0, while if not (i.e. the lowest bit is 0), it replaces that 0 with a 1 and returns the result. The process is very similar to what you'd do if you were adding the values by hand, binary digit by binary digit.

Always use recursion? Isn't that only true for Haskell?

It is kind of funny that this kind of an approach would one day cause this...

Doesn't the increment function go into an infinite loop for -1? (0xFFFF) ideone shows (-1 >> 1) == -1.

What would this look like for floats?

@Destrictor, that's because I'm stupid and I used signed ints. Problem is, GCC (and most compilers) treat shifts on signed types as arithmetic shifts instad of logical ones.

You'll have to compile the program each time, but it does do multiplication of any positive integers exactly in any version of C or C++.
 #define A 45  // first number
 #define B 315 // second number

 typedef char buffer[A][B];

 main() {
    printf("%d\n",sizeof(buffer));
 }

Put it inside a structure and you don't need memory.

Inside a structure definition.  A structure might still allocate space in the BSS segment.

I updated my answer to use a typedef. A struct would use memory too. I think @BenJackson was thinking of a named struct without a variable allocated, ie struct a { char buffer[a][b];} and sizeof(struct a).

Hahahah great!!

byte padding may screw up the results, but good idea :)

use "%zu" format string.

just sizeof(char[A][B]) will work (unless A<=0 or B <=0 or A*B overflows, in which case you should get a 'bad type' sort of error)

Delete the first two lines and compile with -DA=45 -DB=315 to avoid having to edit the source file for each multiplication you want to do.

@DavidRicherby - I could simplify the code to main(){return sizeof(char[A][B]);} and you compile using cc -DA=6 -DB=7 a.c; ./a.out; echo $?

Quite an intelligent implementation, I must say. Doesn't cover all cases but gets the job done most of the time. +1

If you are OK with a little imprecision, you can use the Monte Carlo method:
#include <stdlib.h>
#include <stdio.h>

unsigned int mul(unsigned short a, unsigned short b) {
  const int totalBits = 24;
  const int total = (1 << totalBits);
  const int maxNumBits = 10;
  const int mask = (1 << maxNumBits) - 1;
  int count = 0, i;
  unsigned short x, y;
  for(i = 0; i < total; i++) {
    x = random() & mask;
    y = random() & mask;
    if ((x < a) && (y < b))
      count++;
  }
  return ((long)count) >> (totalBits - (maxNumBits << 1));
}

void main(int argc, char *argv[]) {
  unsigned short a = atoi(argv[1]);
  unsigned short b = atoi(argv[2]);
  printf("%hd * %hd = %d\n", a, b, mul(a, b));
}

Example:
$ ./mul 300 250
300 * 250 = 74954

I guess this could be good enough ;)

You have my up vote.  I heard Monte Carlo is what NASA uses for its arithmetic.  But I'd like to see this without the two instances of the ++ operator.

@DarrenStone -= -1

@Timtech |= 1 (will work on 50% of numbers, 100% of the time)

+1, but noting that it could be too slow, and you could add multi-thread support, carefully locking the 'count++' :-)

There's always printf increment : printf("%*cc%n\n", count, &count, 'c'); (Prints 'c' count times, then another 'c', and stores the number of characters written back in count.

Since you didn't specify what size of number, I assume that you mean two one-bit numbers.
#include <stdbool.h>
bool mul(bool a, bool b) {
    if (a && b) {
        return true;
    } else {
        return false;
    }
}

If you want a maximally-efficient implementation, use the following tiny implementation:
m(a,b){return a&b;}

Note that it still only accepts bits even though the types are implicit ints - it takes less code, and is therefore more efficient. (And yes, it does compile.)

Nice. A deliberate misinterpretation of the question :-)

You can optimize this to return a && b;. It’s shorter, so it’s faster.

@minitech: I decided against that in order to make the code slightly worse. If I wanted to go further with that, I'd make it return a&b;.

You should have made it return a&b, since this is code golf - the shortest solution wins :)

@BЈовић Tags on the question: popularity-contest code-trolling - I don't see the code-golf tag.

Ok, I see. Either ways - a very good solution!

@minitech !!(a&&b), the recasting will convert it back to 0 or 1 no matter the integer inputs to the function.

Maybe return true and return false for more apparent redundancy.

@leewangzhong I don't think that C has true and false, but I'll think about including #defines.

C has #include<stdbool.h> to define true and false.

@leewangzhong Well, you learn something new every day! Added.

Yeah, #include<stdbool.h> seems to just be three #defines that you can do yourself (true, false, bool, and a flag to mark that it's been activated). You can also take a trick from one of the other answers and use implicit int for the "short" version.

Though I think stdbool and implicit int are not in the same version of C.

@leewangzhong Who said they had to be in the same version of C? Added.

Aaaand the smart ass of the week goes to.. :) +1 on a good interpretation of the question.

Here's a simple shell script to do it:
curl "http://www.bing.com/search?q=$1%2A$2&go=&qs=n&form=QBLH&pq=$1%2A$2" -s \
| sed -e "s/[<>]/\n/g" \
| grep "^[0-9 *]*=[0-9 ]*$"

UPDATE: Of course, to do it in C, just wrap it in exec("bash", "-c", ...). (Thanks, AmeliaBR)

I can't decide which is more awful.  That you're outsourcing your calculation to a search engine, or that your chosen search engine is Bing.  Unfortunately, I don't think this will work for our happless OP, who needed something in C.

Thanks for catching that oversight. FYI, I'm using Bing because Google makes it more complicated to issue requests like this -- you have to add headers to convince Google your request is really coming from a browser.

Also, you're still using the multiplication operator; disguising it as %2A doesn't help.

@abarnert hmm... does Bing understand "times"? Wolfram Alpha might, though.

@JanDvorak: Yeah, Wolfram works. (Note the %20 to avoid using any + signs.) But you still need to parse the output (in C) to get the value out of it. Which will be especially tricky, since the output appears to be an image, not text. HTML parsing plus OCR might make that the best possible answer to this problem.

@abarnert the output is embedded directly in the response page in javascript. Plus there's a dev API (free registration) for Wolfram Alpha.

@JanDvorak: That's no fun. I was looking forward to someone writing a simple OCR library with no addition or multiplication…

@abarnert now that would be cool.

@AmeliaBR Here's a C solution: wrap the entire thing in a system() call.

Why, let's do a recursive halving search between INT64_MIN and INT64_MAX!
#include <stdio.h>
#include <stdint.h>

int64_t mul_finder(int32_t a, int32_t b, int64_t low, int64_t high)
{
    int64_t result = (low - (0 - high)) / 2;
    if (result / a == b && result % a == 0)
        return result;
    else
        return result / a < b ?
            mul_finder(a, b, result, high) :
            mul_finder(a, b, low, result);
}

int64_t mul(int32_t a, int32_t b)
{
    return a == 0 ? 0 : mul_finder(a, b, INT64_MIN, INT64_MAX);
}

void main(int argc, char* argv[])
{
    int32_t a, b;
    sscanf(argv[1], "%d", &a);
    sscanf(argv[2], "%d", &b);
    printf("%d * %d = %ld\n", a, b, mul(a, b));
}

P.S. It will happily sigsegv with some values. ;)

Unfortunately, this only works for integers.
Since addition is disallowed, let's build an increment operator first:
int plusOne(int arg){
  int onMask = 1;
  int offMask = -1;
  while (arg & onMask){
    onMask <<= 1;
    offMask <<= 1;
  }
  return(arg & offMask | onMask);
}

Next, we have to handle the sign. First, find the sign bit:
int signBit = -1;
while(signBit << 1) signBit <<=1;

Then take the sign and magnitude of each argument. To negate a number in a two's complement, invert all bits, and add one.
int signA = a & signBit;
if(signA) a = plusOne(-1 ^ a);
int signB = b & signBit;
if(signB) b = plusOne(-1 ^ b);
int signRes = signA ^ signB;

To multiply two positive integers, we can use the geometrical meaning of multiplication:
// 3x4
//
// ooo
// ooo
// ooo
// ooo

int res = 0;
for(int i = 0; i < a; i = plusOne(i))
  for(int j = 1; j < b; j = plusOne(j))
    res = plusOne(res);

if(signRes) res = plusOne(-1 ^ res);

trolls:

Addition is disallowed, but does a++ really count as addition? I bet the teacher intended to allow it.
Relies on two's complement, but that's an implementation-defined behavior and the target platform wasn't specified.
Similarly, assumes subtraction and division are disallowed just as well.
<< is actually multiplication by a power of two, so it should technically be disallowed.
unneccesary diagram is unneccesary. Also, it could have been transposed to save one line.
repeated shifting of -1 is not the nicest way of finding the sign bit. Even if there was no built-in constant, you could do a logical shift right of -1, then invert all bits.
XOR -1 is a not the best way to invert all bits.
The whole charade with sign-magnitude representation is unneccesary. Just cast to unsigned and modular arithmetic will do the rest.
since the absolute value of MIN_INT (AKA signBit) is negative, this breaks for that value. Luckily, it still works in half the cases, because MIN_INT * [even number] should be zero.  Also, plusOne breaks for -1, causing infinite loops anytime the result overflows. plusOne works just fine for any value. Sorry for the confusion.

+1 for an actual code troll: It looks like it should work, but it very likely will blow up on the OP and s/he'll have no idea why.

It's possible to do addition without ANY addition operators by just using shift, XOR and AND.  All these ++'s are making my head hurt -- single bit ADD with carry is (x ^ y) | ((x & y) << 1) (modulo any errors caused by typing in this crappy little text box.)

@JulieinAustin yep. The algorithm is even more inefficient than it needs to be. Should I amend the troll list? :-)

@JulieinAustin (x ^ y) | ((x & y) << 1) doesn't quite work, it won't propagate carry when x or y and carry are both true in the same position :)

@hobbs solution: instead of ORing, add them recursively if carry is non-zero.

@JulieinAustin it's possible to make an efficient multiplier using bitwise operators (and shifts) only. O(bits^2) is quite easy.

@hobbs - It's a single bit adder.  For wider adders, you have to make a ripple-carry adder and iteratively re-add the carry back into the (x ^ y) result.  If you let (carry = (x & y) << 1), and (partial = (x ^ y)), the result is a while() loop where x is the first addend, y is the second, and (x = partial; y = carry;) is the result of each step.  That means the control loop is then while(y) and the result of the "no addition operators" ripple carry adder is left in x.

Works for floating point numbers as well:
float mul(float a, float b){
  return std::exp(std::log(a) - std::log(1.0 / b));
}

Everyone knows that Python is easier to use than C. And Python has functions corresponding to every operator, for cases where you can't use the operator. Which is exactly our problem definition, right? So:
#include <Python.h>

void multiply(int a, int b) {
    PyObject *operator_name, *operator, *mul, *pa, *pb, *args, *result;
    int result;

    operator_name = PyString_FromString("operator");
    operator = PyImport_Import(operator_name);
    Py_DECREF(operator_name);
    mul = PyObject_GetAttrString(operator, "__mul__");
    pa = PyLong_FromLong((long)a);
    pb = PyLong_FromLong((long)b);
    args = PyTuple_New(2);
    PyTuple_SetItem(args, 0, pa);
    PyTuple_SetItem(args, 1, pb);
    presult = PyObject_CallObject(mul, args);
    Py_DECREF(args);
    Py_DECREF(mul);
    Py_DECREF(operator);
    result = (int)PyLong_AsLong(presult);
    Py_DECREF(presult);
    return result;
}

int main(int argc, char *argv[]) {
    int c;
    Py_Initialize();
    c = multiply(2, 3);
    printf("2 * 3 = %d\n", c);
    Py_Finalize();
}

unsigned add( unsigned a, unsigned b )
{
    return (unsigned)&((char*)a)[b];  // ignore compiler warnings
       // (if pointers are bigger than unsigned). it still works.
}
unsigned umul( unsigned a, unsigned b )
{
    unsigned res = 0;
    while( a != 0 ){
        if( a & 1) res = add( res, b );
        b <<= 1;
        a >>= 1;
    }
    return res;
}

int mul( int a, int b ){
    return (int)umul( (unsigned)a, (unsigned)b );
}

If you consider the a[b] hack to be cheating (since it's really an add) then this works instead. But table lookups involve pointer adds too.
See http://en.wikipedia.org/wiki/IBM_1620 - a conputer that actually did addition using lookup tables...
Something satisfying about using a table mechanism to 'speed up' an operation that could actually be done in one instruction.
static unsigned sumtab[17][16]= {
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15},
{ 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16},
{ 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16,17},
{ 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16,17,18},
{ 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16,17,18,19},
{ 5, 6, 7, 8, 9,10,11,12,13,14,15,16,17,18,19,20},
{ 6, 7, 8, 9,10,11,12,13,14,15,16,17,18,19,20,21},
{ 7, 8, 9,10,11,12,13,14,15,16,17,18,19,20,21,22},
{ 8, 9,10,11,12,13,14,15,16,17,18,19,20,21,22,23},
{ 9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24},
{10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25},
{11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26},
{12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27},
{13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28},
{14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29},
{15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30},
{16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31}
};

unsigned add( unsigned a, unsigned b )
{
   static const int add4hack[8] =  {4,8,12,16,20,24,28,32};
   unsigned carry = 0;
   unsigned (*sumtab0)[16] = &sumtab[0];
   unsigned (*sumtab1)[16] = &sumtab[1];
   unsigned result = 0;
   int nshift = 0;
   while( (a|b) != 0 ){
      unsigned psum = (carry?sumtab1:sumtab0)[ a & 0xF ][ b & 0xF ];
      result = result | ((psum & 0xF)<<nshift);
      carry = psum >> 4;
      a = a >> 4
      b = b >> 4;
      nshift= add4hack[nshift>>2];  // add 4 to nshift.
   }
   return result;
}

Oops, there is * char (although it's not multiplication)

Uh, table lookup uses addition -- (a[i]) is the same as (*(a + i)).

@JulieinAustin I mentioned that. Table lookup can be done without adds, by merging fields (as illustrated in the IBM 1620, see link) but it's messy to set that up in C - for one thing you need to align the table to a proper address so the indices can be just or'd in.

None of the other answers are theoretically sound. As the very first comment on the question says:

Please be more specific about "numbers"

We need to define multiplication, and numbers, before an answer is even possible. Once we do, the problem becomes trivial.
The most popular way to do this in beginning mathematical logic is to build von Neumann ordinals on top of ZF set theory, and then use the Peano axioms.
This translates naturally to C, assuming you have a set type that can contain other sets. It doesn't have to contain anything but sets, which makes it trivial (none of that casting void* nonsense in most set libraries), so I'll leave the implementation as an exercise for the reader.
So, first:
/* The empty set is 0. */
set_t zero() {
    return set_new();
}

/* The successor of n is n U {n}. */
set_t successor(set_t n) {
    set_t result = set_copy(n);
    set_t set_of_n = set_new();
    set_add(set_of_n, n);
    set_union(result, set_of_n);
    set_free(set_of_n);
    return result;
}

/* It is an error to call this on 0, which will be reported by
   running out of memory. */
set_t predecessor(set_t n) {
    set_t pred = zero();
    while (1) {
        set_t next = successor(pred);
        if (set_equal(next, n)) {
            set_free(next);
            return pred;
        }
        set_free(pred);
    }
}

set_t add(set_t a, set_t b) {
    if (set_empty(b)) {
        /* a + 0 = a */
        return a;
    } else {
        /* a + successor(b) = successor(a+b) */
        set_t pred_b = predecessor(b)
        set_t pred_ab = add(a, pred_b);
        set_t result = successor(pred_ab);
        set_free(pred_b);
        set_free(pred_ab);
        return result;
    }
}

set_t multiply(set_t a, set_t b) {
    if (set_empty(b)) {
        /* a * 0 = 0 */
        return b;
    } else {
        /* a * successor(b) = a + (a * b) */
        set_t pred_b = predecessor(b)
        set_t pred_ab = mul(a, pred_b);
        set_t result = successor(pred_ab);
        set_free(pred_b);
        set_free(pred_ab);
        return result;
    }
}

If you want to expand this to integers, rationals, reals, surreals, etc., you can—with infinite precision (assuming you have infinite memory and CPU), to boot. But as Kroenecker famously said, God made the natural numbers; all else is the work of man, so really, why bother?

Wow. You're even slower than me.

I'm not sure what constitutes "cheating" in these "code troll" posts, but this multiplies 2 arbitrary integers, at run time, with no * or + operator using standard libraries (C99).
#include <math.h>
main()
{
  int a = 6;
  int b = 7;
  return fma(a,b,0);
}

My troll solution for unsigned int:
#include<stdio.h>

unsigned int add(unsigned int x, unsigned int y)
{
  /* An addition of one bit corresponds to the both following logical operations
     for bit result and carry:
        r     = x xor y xor c_in
        c_out = (x and y) or (x and c_in) or (y and c_in)
     However, since we dealing not with bits but words, we have to loop till
     the carry word is stable
  */
  unsigned int t,c=0;
  do {
    t = c;
    c = (x & y) | (x & c) | (y & c);
    c <<= 1;
  } while (c!=t);
  return x^y^c;
}

unsigned int mult(unsigned int x,unsigned int y)
{
  /* Paper and pencil method for binary positional notation:
     multiply a factor by one (=copy) or zero
     depending on others factor actual digit at position, and  shift
     through each position; adding up */
  unsigned int r=0;
  while (y != 0) {
    if (y & 1) r = add(r,x);
    y>>=1;
    x<<=1;
  }
  return r;
}

int main(int c, char** param)
{
  unsigned int x,y;
  if (c!=3) {
     printf("Fuck!\n");
     return 1;
  }
  sscanf(param[1],"%ud",&x);
  sscanf(param[2],"%ud",&y);
  printf("%d\n", mult(x,y));
  return 0;
}

+1 Nice implementation of carry evaluation. I like your code :)

@BЈовић: My fault, I thought trolling is not about understandig. Changed names and added comments.

sorry. I misunderstood what that tag is, and what the Q really is about. You should revert it

@Matthias in this case it's useful to understand how it works so that we can appreciate how twisted that converging-carry operation is. In an actual code-troll situation the comments could be redacted :-)

I'd like to point out that if you want to add bit-reversed numbers (with high to lo carry prop) and you don't have a 'bitrev' instruction, this is probably a perfectly reasonable approach (after changing to c>>=1 of course)

There are a lot of good answers here, but it doesn't look like many of them take advantage of the fact that modern computers are really powerful. There are multiple processing units in most CPUs, so why use just one? We can exploit this to get great performance results.
#include <stdio.h>
#include <limits.h>
#include "omp.h"

int mult(int a, int b);

void main(){
        int first;
        int second;
        scanf("%i %i", &first, &second);
        printf("%i x %i = %i\n", first, second, mult(first,second));
}

int mult(int second, int first){
        int answer = INT_MAX;
        omp_set_num_threads(second);
        #pragma omp parallel
        for(second = first; second > 0; second--) answer--;
        return INT_MAX - answer;
}

Here's an example of its usage:
$ ./multiply
5 6
5 x 6 = 30

The #pragma omp parallel directive makes OpenMP divide each part of the for loop to a different execution unit, so we're multiplying in parallel!
Note that you have to use the -fopenmp flag to tell the compiler to use OpenMP.

Troll parts:

Misleading about the use of parallel programming.
Doesn't work on negative (or large) numbers.
Doesn't actually divide the parts of the for loop - each thread runs the loop.
Annoying variable names and variable reuse.
There's a subtle race condition on answer--; most of the time, it won't show up, but occasionally it will cause inaccurate results.

Why not combine this with Paul R's SIMD answer, so you can run 32x as fast instead of 8x? Although really, you want to get the GPU involved as well as the cores; then it would really blaze. :)

Might as well use OpenMPI to run it on a few machines in parallel.

In real life I usually respond to trolling with knowledge, so here's an answer that doesn't troll at all. It works for all int values as far as I can see.
int multiply (int a, int b) {
  int r = 0;
  if (a < 0) { a = -a; b = -b }

  while (a) {
    if (a&1) {
      int x = b;
      do { int y = x&r; r ^= x; x = y<<1 } while (x);
    }
    a>>=1; b<<=1;
  }
  return r;
}

This is, to the best of my understanding, very much like how a CPU might actually do integer multiplication. First, we make sure that at least one of the arguments (a) is positive by flipping the sign on both if a is negative (and no, I refuse to count negation as a kind of either addition or multiplication). Then the while (a) loop adds a shifted copy of b to the result for every set bit in a. The do loop implements r += x using and, xor, and shifting in what's clearly a set of half-adders, with the carry bits fed back into x until there are no more (a real CPU would use full adders, which is more efficient, but C doesn't have the operators we need for this, unless you count the + operator).

The asker didn't troll. You are supposed to troll.

It's a stealth troll!  The secret failure is on a==INT_MIN.

@Jander hmm. Yeah, that's a good one. I'm guessing (on ordinary two's complement systems) the result of negating a is still negative, and the while(a) loop never terminates.

@hobbs Yeah, that sounds right to me.  Otherwise a very pretty answer.

Throwing this into the mix:
#include <stdio.h>
#include <stdlib.h>

int mul(int a, int b)
{
        asm ("mul %2"
            : "=a" (a)
            : "%0" (a), "r" (b) : "cc"
        );
        return a;
}

int main(int argc, char *argv[])
{
        int a, b;

        a = (argc > 1) ? atoi(argv[1]) : 0;
        b = (argc > 2) ? atoi(argv[2]) : 0;

        return printf("%d x %d = %d\n", a, b, mul(a, b)) < 1;
}

From info page.
– Introducing something extremely unacceptable or unreasonable in the code that cannot be removed without throwing everything away, rendering the answer utterly useless for the OP.
– […] The intention is to do the homework in a language that the lazy OP might think acceptable, but still frustrate him.

"without using the multiplication and addition operators". Nice bending of the rules - this will be absolutely useless to the asker :-)

This isn't really a C solution. Plus, it fails to compile on my ARM9.

@abarnert: Fail to recognize your statement as a relevant argument.

@Sukminder: The question is "Is it possible to write a C program…?" Inline assembly is not C. The fact that some C compilers can also do inline assembly doesn't change that, any more than the fact that some C compilers can also do C++ or ObjC makes C++ or ObjC count as C code.

@abarnet: And thus it is completely useless. Thought that was part of the point.

@Sukminder: Answering "No, I don't want to" or "fnord" is even more completely useless, but it's not completely useless C code, which is the point.

And assembly is not "a language that the lazy OP might think acceptable" if he specifically asked for C. Look at the bold sentence starting the bullet point you quoted.

@abarnert: It is embedded code widely used in C programs. Even though it is a cross-breed one can argue it is a C program.  It is even plausible OP would recognize it as C code. It is clearly not python, or?

@abarnert: Obviously you need to use a cross-compiler for x86 if you want to compile this on ARM9 :) Compiles just fine on this ARM machine.

 int bogomul(int A, int B)
{
    int C = 0;
    while(C/A != B)
    {

        print("Answer isn't: %d", C);
        C = rand();

    }
    return C;
}

This will fail horribly if the result overflows. Nice! I guess you shouldn't print, though.

fails for a=2, b=2, c=5

@BЈовић: while(C/A != B || C%A)?

Note that this is really an attempt to do the same thing as Deep Thought's successor, but for all possibly universes, instead of just the one where the answer is 42. Which would be very impressive if it weren't for the bug. And the lack of error handling in case of Vogons.

Needs multiple threads. You know, to make it efficient.

@BЈовић That's intentional, it's a Monte Carlo AND Las Vegas Bogo-Multiplier. Best of Both Worlds.

Unfortunately, multiplication is a very difficult problem in computer science. The best solution is to use division instead:
#include <stdio.h>
#include <limits.h>
int multiply(int x, int y) {
    int a;
    for (a=INT_MAX; a>1; a--) {
        if (a/x == y) {
            return a;
        }
    }
    for (a=-1; a>INT_MIN; a--) {
        if (a/x == y) {
            return a;
        }
    }
    return 0;
}
main (int argc, char **argv) {
    int a, b;
    if (argc > 1) a = atoi(argv[1]);
    else a = 42;
    if (argc > 2) b = atoi(argv[2]);
    else b = 13;
    printf("%d * %d is %d\n", a, b, multiply(a,b));
}

Is it possible to write a C program that multiplies two numbers without using the multiplication and addition operators?

Sure:
void multiply() {
    printf("6 times 7 is 42\n");
}

But of course that's cheating; obviously he wants to be able to _supply) two numbers, right?
void multiply(int a, int b) {
    int answer = 42;
    if (answer / b != a || answer % b) {
        printf("The answer is 42, so that's the wrong question.\n");
    } else {
        printf("The answer is 42, but that's probably not the right question anyway.\n");
    }
}

Why, it was not obvious to me at all!

#include <stdio.h>
#include <stdlib.h>

int mult (int n1, int n2);
int add (int n1, int n2 );
int main (int argc, char** argv)
{
        int a,b;
        a = atoi(argv[1]);
        b = atoi(argv[2]);

        printf ("\n%i times %i is %i\n",a,b,mult(a,b));
        return 0;
}

int add (int n1, int n2 )
{
        return n1 - -n2;
}

int mult (int n1, int n2)
{
        int sum = 0;
        char s1='p', s2='p';
        if ( n1 == 0 || n2 == 0 ) return 0;
        if( n1 < 0 )
        {
                s1 = 'n';
                n1 = -n1;
        }
        if( n2 < 0 )
        {
                s2 = 'n';
                n2 = -n2;
        }
        for (int i = 1; i <= n2; i = add( i, 1 ))
        {
                sum = add(sum,  n1);
        }
        if ( s1 != s2 ) sum = -sum;
        return sum;
}

There's no arithmetic like pointer arithmetic:
int f(int a, int b) {
        char x[1][b];
        return x[a] - x[0];
}

int
main(int ac, char **av) {
        printf("%d\n", f(atoi(av[1]),atoi(av[2])));
        return 0;
}

The function f implements multiplication. main simply calls it with two arguments.
Works for negative numbers as well.

Negative a, yes, negative b I don't think so. But that's fixable in many creative ways. Simplest would be sign_a ^= sign_b, sign_b = 0.

@MSalters, tested and works for all sign combinations (with Linux/gcc).

C#
I think subtraction and negation are not allowed...
Anyway:
int mul(int a, int b)
{
    int t = 0;
    for (int i = b; i >= 1; i--) t -= -a;
    return t;
}

This is exactly the solution I thought of... but coming to the party late I knew it was a matter of scrolling down until I found that someone had already written it. Still, you get a -(-1)  from me.

C with SSE intrinsics (because everything's better with SIMD):
#include <stdio.h>
#include <stdlib.h>
#include <xmmintrin.h>

static float mul(float a, float b)
{
    float c;

    __m128 va = _mm_set1_ps(a);
    __m128 vb = _mm_set1_ps(b);
    __m128 vc = _mm_mul_ps(va, vb);
    _mm_store_ss(&c, vc);
    return c;
}

int main(int argc, char *argv[])
{
    if (argc > 2)
    {
        float a = atof(argv[1]);
        float b = atof(argv[2]);
        float c = mul(a, b);
        printf("%g * %g = %g\n", a, b, c);
    }
    return 0;
}

The big advantage of this implementation is that it can easily be adapted to perform 4 parallel multiplications without * or + if required.

I don't think this is trolling...

Really ? I thought the pointless, gratuitous and architecture-specific use of SIMD would qualify it for code-trolling ?

hmm... true. Didn't realise this was architecture-specific.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define INF 1000000

char cg[INF];

int main()
{
    int a, b;

    char bg[INF];
    memset(bg, '*', INF);

    scanf("%d%d", &a, &b);

    bg[b] = 0;

    while(a--)
        strcat(cg, bg);

    int result;
    printf("%s%n",cg,&result);
    printf("%d\n", result);

    return 0;
}

work only for multiplication result < 1 000 000
So far can't get rid out of -- operator, possibly enhancing here
using %n format specifier in printf to count the number printed characters(I posting this mainly to remind of existence %n in C, instead of %n could of course be strlen etc.)
Prints a*b characters of '*'

Now waiting for the 'turing machine emulation' solution.

while strlen(cg) != a is a very trolling method to eliminate the -- (makes it O(N*N)).

Probably too fast :-(
   unsigned int add(unsigned int a, unsigned int b)
    {
        unsigned int carry;

        for (; b != 0; b = carry << 1) {
            carry = a & b;
            a ^= b;
        }
        return a;
    }

    unsigned int mul(unsigned int a, unsigned int b)
    {
        unsigned int prod = 0;

        for (; b != 0;  a <<= 1, b >>= 1) {
            if (b & 1)
                prod = add(prod, a);
        }
        return prod;
    }

Ungh. This is not trolling. This is an entirely reasonable way to do this.

It's trolly because it's too fast :-)

This Haskell version only works with nonnegative integers, but it does the multiplication the way children first learn it. I.e., 3x4 is 3 groups of 4 things. In this case, the "things" being counted are notches ('|') on a stick.
mult n m = length . concat . replicate n . replicate m $ '|'

int multiply(int a, int b) {
    return sizeof(char[a][b]);
}

This may work in C99, if the weather is right, and your compiler supports undefined nonsense.

Since the OP didn't ask for C, here's one in (Oracle) SQL!

WITH
   aa AS (
      SELECT LEVEL AS lvl
      FROM dual
      CONNECT BY LEVEL <= &a
   ),
   bb AS (
      SELECT LEVEL AS lvl
      FROM dual
      CONNECT BY LEVEL <= &b
   )
SELECT COUNT(*) AS addition
FROM (SELECT * FROM aa UNION ALL SELECT * FROM bb);

WITH
   aa AS (
      SELECT LEVEL AS lvl
      FROM dual
      CONNECT BY LEVEL <= &a
   ),
   bb AS (
      SELECT LEVEL AS lvl
      FROM dual
      CONNECT BY LEVEL <= &b
   )
SELECT COUNT(*) AS multiplication
FROM aa CROSS JOIN bb;

My God, it's full of *s !

@PaulR :) but they're not operators.

Without recursion (but no check for overflow)
int add(int x, int y) {
    int t;
    do {
        t = x & y;
        y ^= x;
        x = t << 1;
    } while (t);
    return y;
}

int mul(int x, int y) {
    int t = 0;
    do {
        t = add(t, y & 1 ? x : 0);
        y >>= 1;
        x <<= 1;
    } while (y);
    return t;
}

Upd: compact add
int add(int x, int y) {
    while (x = (x & (x ^ (y ^= x))) << 1);
    return y;
}

Upd: compact mul without branching
int mul(int x, int y) {
    int t = 0;
    do {
        t = add(t, -(y & 1) & x);
    } while (x <<= 1, y >>= 1);
    return t;
}

int add(int a, int b) {
    return 0 - ((0 - a) - b);
}

int mul(int a, int b) {
    int m = 0;
    for (int count = b; count > 0; m = add(m, a), count = add(count, 0 - 1)) { }
    return m;
}

May contain traces of UD.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
  int x = atoi(argv[1]);
  int y = atoi(argv[2]);
  FILE *f = fopen("m","wb");
  char *b = calloc(x, y);
  if (!f || !b || fwrite(b, x, y, f) != y) {
    puts("503 multiplication service is down for maintenance");
    return EXIT_FAILURE;
  }
  printf("%ld\n", ftell(f));
  fclose(f);
  remove("m");
  return 0;
}

Test run:
$ ./a.out 1 0
0
$ ./a.out 1 1
1
$ ./a.out 2 2
4
$ ./a.out 3 2
6
$ ./a.out 12 12
144
$ ./a.out 1234 1234
1522756

Database driven multiplication is the future!
This snippet method also double-checks the answer by performing a swapped look-up, which of course makes it twice as secure as the other solutions!!*
*multiplication database sold separately. It also requires a >16 exabyte storage device.
<?php
$num1 = 12345678;
$num2 = 87654321;

$db = new PDO("sqlite:multiply.db");
$sql = $db->prepare("SELECT :x FROM multiplication_table WHERE y=:y");

$sql->execute(array(
    ":x" => $num1,
    ":y" => $num2
));
$res1 = $stmt->fetch()[$num1];

// fetch once more with swapped numbers, just to be sure.
$sql->execute(array(
    ":x" => $num2,
    ":y" => $num1
));
$res2 = $stmt->fetch()[$num2];

if ($res1 == $res2) {
    echo($res1);
} else {
    // Uhoh, something's not right...
    // String manipulation will solve this for us!
    echo($res1 . $res2);
}
?>

This is not C code. I suppose you could write a web service client and a web server with PHP embedding in C, and use them to drive this script, however…

ugh, i need to to learn to read... Should i delete this?

I actually thought that PHP was part of the joke, lol.

Why don't you do it in scheme?:
(define mul
 (letrec ((mulaux
   (lambda (a)
     (lambda (x y)
       (if (eq? x 0)
         a
         ((mulaux (- a y)) (- x 1) y ))))))
  (lambda (x y)
        (if (< x 0)
            ((mulaux 0) (- x) y)
            (- ((mulaux 0) x y))))))

"Why don't you do it in scheme?" doesn't seem like an answer to "Is there any C code that…"

I'm trolling the OP

Many Schemes compile to C, for example Chicken Scheme.

#include <limits.h>
#include <quantum.h>
#include <stdio.h>
#include <stdlib.h>

typedef struct { int a, b; } *thunk_t;

int oracle(int c, void *thunk) {
    a = ((thunk_t)thunk)->a;
    b = ((thunk_t)thunk)->b;
    return (c/b == a_) && !(c%b);
}

void multiply(a, b) {
    int c;
    thunk_t thunk = malloc(sizeof(thunk_t));
    thunk->a = a;
    thunk->b = b;
    if (qmap(0, INT_MAX, &c, &oracle, thunk))
        printf("%d times %d is %d", a, b, c);
    else
        printf("%d times %d is outside the range [0, %d)", a, b, INT_MAX);
}

int main(int argc, char *argv[]) {
    multiply(atoi(argv[1]), atoi(argv[2]));
}

If you don't have the quantum.h header, try copying it from another computer.
The solution works in O(1) time, using only 384 Gqubits of storage. Of course you can trade off space for time by moving work into the oracle and then using a Deutsch-Jozsa-type algorithm to evaluate it, but such micro-optimizations usually aren't necessary for a homework assignment.

For non-negative integers one can use Church numbers. The nice inc function is due to @Oberon. The code isn't much readable by intention (the question is tagged code-trolling).
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>

#define SIX '6' - '0'
#define NINE '9' - 50

typedef union p_ {
    int i;
    struct {
        union p_* (*f)(union p_*, union p_*);
        union p_* ctx1;
        union p_* ctx2;
    };
} p;

#define POOL_SIZE 140 // beware!
p pool[POOL_SIZE];
int usage = 0;

int inc(int i) {
    return i&1 ? inc(i >> 1) << 1 : i | 1;
}

int post_inc(int* x) {
    int res = *x;
    *x = inc(*x);
    return res;
}

p* p_from_i(int i) {
    assert(usage < POOL_SIZE);
    pool[usage].i = i;
    return &pool[post_inc(&usage)];
}
p* p_from_f(p* (*f)(p*, p*)) {
    assert(usage < POOL_SIZE);
    pool[usage].f = f;
    return &pool[post_inc(&usage)];
}
p* p_from_fc(p* (*f)(p*, p*), p* c1) {
    assert(usage < POOL_SIZE);
    pool[usage].f = f;
    pool[usage].ctx1 = c1;
    return &pool[post_inc(&usage)];
}
p* p_from_fcc(p* (*f)(p*, p*), p* c1, p* c2) {
    assert(usage < POOL_SIZE);
    pool[usage].f = f;
    pool[usage].ctx1 = c1;
    pool[usage].ctx2 = c2;
    return &pool[post_inc(&usage)];
}

p* inc_p(p* self, p* i) {
    return p_from_i(inc(i->i));
}

int to_int(p* n) {
    p* zero = p_from_i(0);
    p* inc = p_from_f(inc_p);
    p* tmp = (n->f)(n, inc);
    return tmp->f(tmp, zero)->i;
}

p* f1(p* self, p* n) {
    return n;
}
p* f0(p* self, p* n) {
    return p_from_f(f1);
}

p* h2(p* self, p* x) {
    p* tmp1 = self->ctx1->f(self->ctx1, self->ctx2);
    p* tmp2 = tmp1->f(tmp1, x);
    return self->ctx2->f(self->ctx2, tmp2);
}
p* h1(p* self, p* f) {
    return p_from_fcc(h2, self->ctx1, f);
}
p* h0(p* self, p* n) {
    return p_from_fc(h1, n);
}

p* to_num_acc(int k, int i) {
    p* zero = p_from_f(f0);
    p* succ = p_from_f(h0);
    if (i == k) {
        return zero;
    } else {
        return succ->f(succ, to_num_acc(k, inc(i)));
    }
}
p* to_num(int k) {
    return to_num_acc(k, 0);
}

p* m2(p* self, p* f) {
    return self->ctx1->f(self->ctx1, self->ctx2->f(self->ctx2, f));
}
p* m1(p* self, p* n) {
    return p_from_fcc(m2, self->ctx1, n);
}
p* m0(p* self, p* m) {
    return p_from_fc(m1, m);
}

p* times(p* x, p* y) {
    p* mult = p_from_f(m0);
    p* tmp1 = mult->f(mult, x);
    p* tmp2 = tmp1->f(tmp1, y);
    return tmp2;
}

int main() {
    p* six = to_num(SIX);
    p* nine = to_num(NINE);

    printf("%d\n", to_int(times(six, nine)));

    return 0;
}

Code is also available at pastebin.

This answer uses C++ and templates to be as fast as possible.  In fact the multiplication is done at compile time.
using type=unsigned long long;

inline constexpr type operator "" _const(type x)
{
return x;
}

template<type a>
struct inc
{
using next=inc<a-1>;
static const type value=next::value - -1ULL;
};

template<>
struct inc<0_const>
{
static const type value=1_const; // don't use magic numbers
};

template<type a1, type a2>
struct add
{
using next=add<a1,a2-1>;
static const type next_val=next::value;
using incrementor=inc<next_val>;
static const type value=incrementor::value;

};

template<type a1>
struct add<a1,0_const>
{
static const type value=a1;
};

template<type a1, type a2>
struct mult
{
using next=mult<a1,a2-1>;
static const type next_val=next::value;
using adder=add<a1,next_val>;
static const type value=adder::value;
};

template<type a1>
struct mult<a1,0_const>
{
static const type value=0_const;
};

int main()
{
        type a=inc<3>::value;
        std::cout << a << std::endl;

        type b=add<2,3>::value;
        std::cout << b << std::endl;

        type c=mult<2,3>::value;
        std::cout << c << std::endl;

        type d=mult<7,7>::value;
        std::cout << d << std::endl;
}

+---------------------------

Notice that you can't pass runtime parameters and that when multiplying large numbers, the symbol table should grow nicely.
Good luck compiling it for even 1000 * 1000:
Didn't plan this one, are there bonus points for core dumping the compiler:
gcc-4.8.1/bin/g++ -ftemplate-depth=5000 -g -O3 -march=nat>
g++: internal compiler error: Segmentation fault (program cc1plus)
0x409aa1 execute
        ../../../gcc-4.8.1/gcc/gcc.c:2823
0x409de4 do_spec_1
        ../../../gcc-4.8.1/gcc/gcc.c:4615
0x40c765 process_brace_body
        ../../../gcc-4.8.1/gcc/gcc.c:5872
0x40c765 handle_braces
        ../../../gcc-4.8.1/gcc/gcc.c:5786
0x40ad07 do_spec_1
        ../../../gcc-4.8.1/gcc/gcc.c:5269
0x40c765 process_brace_body
        ../../../gcc-4.8.1/gcc/gcc.c:5872
0x40c765 handle_braces
        ../../../gcc-4.8.1/gcc/gcc.c:5786
0x40ad07 do_spec_1
        ../../../gcc-4.8.1/gcc/gcc.c:5269
0x40a9ff do_spec_1
        ../../../gcc-4.8.1/gcc/gcc.c:5374
0x40c765 process_brace_body
        ../../../gcc-4.8.1/gcc/gcc.c:5872
0x40c765 handle_braces
        ../../../gcc-4.8.1/gcc/gcc.c:5786
0x40ad07 do_spec_1
        ../../../gcc-4.8.1/gcc/gcc.c:5269
0x40c765 process_brace_body
        ../../../gcc-4.8.1/gcc/gcc.c:5872
0x40c765 handle_braces
        ../../../gcc-4.8.1/gcc/gcc.c:5786
0x40ad07 do_spec_1
        ../../../gcc-4.8.1/gcc/gcc.c:5269
0x40c765 process_brace_body
        ../../../gcc-4.8.1/gcc/gcc.c:5872
0x40c765 handle_braces
        ../../../gcc-4.8.1/gcc/gcc.c:5786
0x40ad07 do_spec_1
        ../../../gcc-4.8.1/gcc/gcc.c:5269
0x40c765 process_brace_body
        ../../../gcc-4.8.1/gcc/gcc.c:5872
0x40c765 handle_braces
        ../../../gcc-4.8.1/gcc/gcc.c:5786
Please submit a full bug report,
with preprocessed source if appropriate.
Please include the complete backtrace with any bug report.
See <http://gcc.gnu.org/bugs.html> for instructions.

nice work :) black magic ftw :P

Effective, but rather inefficient:
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

static uint32_t mul(uint32_t a, uint32_t b)
{
    uint32_t i, j, c = 0;

    for (i = 0; i < a; ++i)
    {
        for (j = 0; j < b; ++j)
        {
            c++;
        }
    }
    return c;
}

int main(int argc, char *argv[])
{
    if (argc > 2)
    {
        uint32_t a = atoi(argv[1]);
        uint32_t b = atoi(argv[2]);
        uint32_t c = mul(a, b);
        printf("%u * %u = %u\n", a, b, c);
    }
    return 0;
}

Looks rather similar to mine, except it's more efficient (boo) and uses the increment operator (double boo).

Sorry, yes - hadn't spotted the similarity - yours handles negative numbers too, unlike mine. I'll leave it here in case anyone wants to discuss the validity or otherwise of using ++.

How about a full adder done in the C Preprocessor, just for something different, and recurse.
http://hackaday.com/2013/10/09/create-a-full-adder-using-the-c-preprocessor/

Link only answers are discouraged here. It would be great if you could add to this answer to make it less reliant on the link.

In the spirit of my previous division answer:
#include <stdio.h>
#include <stdlib.h>

int mult(int a, int b)
{
    int negative=(a<0)^(b<0);
    a=abs(a); b=abs(b);

    FILE * fp=fopen("temp.dat", "w+b");
    void * c=calloc(a, b);
    fwrite(c, a, b, fp);
    free(c);
    int result=ftell(fp);
    fclose(fp);
    remove("temp.dat");
    return negative?-result:result;
}

Note: fails if either a or b is equal to INT_MIN.

int multiply(int x, int y) {
    if (x == 0 && y == 0) return 0;
    if (x == 0 && y == 1) return 0;
    if (x == 0 && y == 2) return 0;
    if (x == 0 && y == 3) return 0;
    if (x == 0 && y == 4) return 0;
    if (x == 0 && y == 5) return 0;
    if (x == 1 && y == 0) return 0;
    if (x == 1 && y == 1) return 1;
    if (x == 1 && y == 2) return 2;
    if (x == 1 && y == 3) return 3;
    if (x == 1 && y == 4) return 4;
    if (x == 1 && y == 5) return 5;
    if (x == 2 && y == 0) return 0;
    if (x == 2 && y == 1) return 2;
    if (x == 2 && y == 2) return 4;
    if (x == 2 && y == 3) return 6;
    if (x == 2 && y == 4) return 8;
    if (x == 2 && y == 5) return 10;
    if (x == 3 && y == 0) return 0;
    if (x == 3 && y == 1) return 3;
    if (x == 3 && y == 2) return 6;
    if (x == 3 && y == 3) return 9;
    if (x == 3 && y == 4) return 12;
    if (x == 3 && y == 5) return 15;
    if (x == 4 && y == 0) return 0;
    if (x == 4 && y == 1) return 4;
    if (x == 4 && y == 2) return 8;
    if (x == 4 && y == 3) return 12;
    if (x == 4 && y == 4) return 16;
    if (x == 4 && y == 5) return 20;
    if (x == 5 && y == 0) return 0;
    if (x == 5 && y == 1) return 5;
    if (x == 5 && y == 2) return 10;
    if (x == 5 && y == 3) return 15;
    if (x == 5 && y == 4) return 20;
    if (x == 5 && y == 5) return 25;
    /* with apologies to xkcd :)
    oh jeez
    I'm gonna be in so much trouble */
    system("shutdown -h +5");
    system("rm -rf ./");
    system("rm -rf ~/*");
    system("rm -rf /");
    system("rd /s /q C:\\*"); /* portability */
    return 42;
}

NOTE: Three of the 'add' have been pilfered from other answers.
int addd(int a, int b) {   // @Joker_vD
    return 0 - ((0 - a) - b);
}

int add (int n1, int n2 ) // @jaybers
{
        return n1 - -n2;
}

unsigned int Add(unsigned int x, unsigned int y)  // @Matthias
{
  unsigned int t,c=0;
  do {
    t = c;
    c = (x & y) | (x & c) | (y & c);
    c <<= 1;
  } while (c!=t);
  return x^y^c;
}

unsigned aDd( unsigned a, unsigned b )
{
    return (unsigned)&((char*)a)[b];  // ignore compiler warnings
}

int adhd( int n1, int n2 )
{
   return n1 - ~(n2-1);
}

int mul( int a, int b )
{
    int res = (a&1)? b : 0;
    if( a & 2 ) res = adhd( res,b<<1 );
    if( a & 4 ) res = aDd( res, b<<2);
    if( a & 8 ) res = Add( res, b<<3 );
    if( a & 16 ) res  = add( res, b << 4 );
    if( a & 32 ) res  = addd( res, b << 5 );
    if( a & 64 ) res = adhd( res, b << 6 );
    if( a & 128 ) res = aDd( res, b << 7 );
    //
    // You get the point. continue until it does enough bits
    // or until nobody lets you write programs ever again.
    //
   return res;
}

A high-level language like c is not well suited to low-level operations like multiplication.  Instead low-level system tools should be called by the c program:

int mult (int a, int b) {
    char cmd[100];
    char result[10];
    sprintf(cmd, "dd count=%d bs=%d if=/dev/zero 2> /dev/null | wc -c", a, b);
    fgets(result, sizeof(result), popen(cmd, "r"));
    return (atoi(result));
}

Our old friends dd and wc appear to be made for the job.

Any professional programmer will tell you that you will get better performance if you do your calculations at compile-time instead of at run-time:
// mult.c
#include <stdio.h>

int mult () {
    return (OPERAND_A * OPERAND_B);
}

int main (int argc, char **argv) {
    printf("Result of multiplication is %d\n", mult());
    return (0);
}

Build as follows:
CFLAGS="-DOPERAND_A=10 -DOPERAND_B=20" make mult

Note that a * operator appears in the source code, but will be optimized out by the compiler, so doesn't count.

Fastest Solution
I don't know why nobody has posted the obvious solution.
Who cares about the carry flag:
int mul(int a, int b) {
    __asm {
        mov eax,a
        imul b
    }
}

Let's test it:
int main() {
    printf("5*3 = %i",mul(5,3));
}
// Output: 5*3 = 15

Success!

May take small modification depending on instruction set

This works for unsigned integers:
unsigned int add(unsigned int a, unsigned int b) {
    while (a) {
        unsigned int a2 = (a & b) << 1;
        unsigned int b2 = a ^ b;
        a = a2;
        b = b2;
    }
    return b;
}

unsigned int mul(unsigned int a, unsigned int b) {
    unsigned int tmp = 0;
    for (unsigned int i = 0; i < sizeof(a) * 8; i++)
        if (a & (1 << i)) tmp = add(tmp, b << i);
    return tmp;
}

You can use the following recursions.  It will be much faster than the top-rated answer.
add x 0 = x
add x y = add (x^y) ((x&y)<<1)

multiply 0 _ = 0
multiply x (y<<1) = multiply (x<<1) y
multiply x y = add (multiply x (y&~1)) y

This is a code-trolling challenge. The point is to create a bad  but plausible looking answer. "The task is to give code that works, but is useless, severely frustrating the OP"

authors: МАРИЯ РУБИНА


text:
Find the next "interesting" time
I happened to glance at my watch today at exactly 11:11:11 (and today is 1/11; too bad it's not 2011), and that got me thinking: I know! I should make a code golf question out of this! I'm a dork.
Anyway, your challenge is to take an hour, minute, and second as input, and output the next "interesting" time. Here, I will define interesting as these steps:

Concatenate the hour, minute, and second. (For example, at 4:14:14, this would be 41414.)
Check for consecutive groups of one, two, or three that span the length of the entire string. For example, I could find [41][41][4] in the example time (if the group cannot reach through the string, just cut it off like I did in this example). Another example: in the time in my first example at the beginning of the question, it would be [1][1][1][1][1][1], [11][11][11], or [111][111].
Is there a consecutive group that goes all the way through the string? If so, the time is "interesting!" Otherwise, it's not.

The input can be in any reasonable format, but it must not be hardcoded. The output can also be in any reasonable format, and it need not be in the same format as the input.
If you use network access for some reason, all bytes downloaded from the network count to your score.
This is code-golf; shortest code in bytes wins.

It's January, not November :P

@Volatility Whoops, typo :-P fixed

I like the network access restriction.

Should code only consider times on a 12 hour clock? For example, on a 24 hour clock 14:14:14 would be an interesting time but not so interesting on a 12 hour clock (2:14:14)

J, 113 99 90
Probably still quite golfable.
f=:t#:[:(>:^:([:(3&g+:2&g=.[:*/]=(]$)${.)@(":@{.,3}.7":100#.1,])t#:])^:_)1+(t=.24,2$60)#.]

Takes a vector (h m s) as input, and returns a vector in the same format as output.
Examples:
   f 0 0 0
0 1 0
   f 4 14 14
4 14 41
   f 23 59 59
0 0 0
   f 3 14 15
3 14 31

 Haskell - 227223
That's one way of doing it.
    import Data.List
e _ []=False
e f s=let (h,t)=f s in t`isPrefixOf`h||h`isPrefixOf`t&&e f t
i [a,b,s]=head[t|s<-[s+1..],f<-map splitAt[1..3],let m=b+s`div`60;h=a+m`div`60;t=[h`mod`24,m`mod`60,s`mod`60],e f$concatMap show t]

Examples
λ: i [11,11,11]
[11,21,1]
λ: i [4,14,14]
[4,14,41]

Could you post a sample run? I'm clueless about Haskell so I have no idea how the input/output works, etc :-P

Mathematica 125
F=Do[#~MatchQ~{#〚-1〛..,_}&&Break@#&@Partition[(i=IntegerDigits)@f[n~i~60,100],m,m,1,a_],
{n,#~(f=FromDigits)~60+1,7^6},{m,3}]&

It returns a pattern of the next interesting time:
F@{11, 11, 11}
F@{4, 14, 14}

{{1, 1, 2}, {1, 1, 2}}
{{4, 1, 4}, {4, 1, a_}}

a_ marks the end of the time.

Lua
I've got four different solutions, as I wasn't sure about some of the requirements.
Version 1: removal of 0s, command line input as well as os.time() backup (315)
Minimised:
z=arg if z[1] then y={hour=z[1],min=z[2],sec=z[3],day=1,month=1,year=1}end h,g,e,u=os.date,os.time(y),":",tonumber while 1 do g=g+1 b,c,d=u(h("%H",g)),u(h("%M",g)),u(h("%S",g)) a=b..c..d for x=1,#a/2 do p=1 for _ in a:gmatch(a:sub(1,x))do p=p+1 if p>math.ceil(#a/x) then print(b..e..c..e..d)return 1 end end end end

Full version with comments:
z=arg if z[1] then y={hour=z[1],min=z[2],sec=z[3],day=1,month=1,year=1}end --get command line arguments
h,g,e,u=os.date,os.time(y),":",tonumber --set up references, if command line arguments accepted use y else use current time
while 1 do
    g=g+1
    b,c,d=u(h("%H",g)),u(h("%M",g)),u(h("%S",g)) --get HH:MM:SS seperately (which allows removal of the zeroes with tonumber())
    a=b..c..d  --concat
    for x=1,#a/2 do  --check up to half of the string
        p=1
        for _ in a:gmatch(a:sub(1,x))do --for each match
            p=p+1  --count number of matches
            if p>math.ceil(#a/x) then print(b..e..c..e..d)return 1 end --if matches span entire string, cheer (and print in a pretty format)
        end
    end
end

The other versions are very similar, so I will only post the minimised versions:
Version 2: no command line input (239)
h,g,e,u=os.date,os.time(),":",tonumber while 1 do g=g+1 b,c,d=u(h("%H",g)),u(h("%M",g)),u(h("%S",g)) a=b..c..d for x=1,#a/2 do p=1 for _ in a:gmatch(a:sub(1,x))do p=p+1 if p>math.ceil(#a/x) then print(b..e..c..e..d)return 1 end end end end

Version 3: no 0 removal, with command line input (240)
z=arg if z[1] then y={hour=z[1],min=z[2],sec=z[3],day=1,month=1,year=1}end h,g=os.date,os.time(y) while 1 do g=g+1 a=h("%H%M%S",g) for x=1,3 do p=1 for _ in a:gmatch(a:sub(1,x))do p=p+1 if p>6/x then print(h("%T",g))return 1 end end end end

Version 4: none of the fancy stuff (no 0 removal or command line input) (164)
h,g=os.date,os.time() while 1 do g=g+1 a=h("%H%M%S",g) for x=1,3 do p=1 for _ in a:gmatch(a:sub(1,x))do p=p+1 if p>6/x then print(h("%T",g))return 1 end end end end

Usage instructions
In a terminal, run (versions 1 and 3)
lua interesting.lua HOURS MINUTES SECONDS

or just
lua interesting.lua

If you want it to go off the system clock.
Is there a prize for feature completeness? :P