text:
"list comprehension" in php.
PHP has closures, let's play around with them.
I have some arrays similar to, $wannabelist = array (1, 2, 3, 4, 5, 6).
I want to do this: compr( expression($params), $wannabelist, $wannabilist2 ...).
compr() should do the following:

Take all the possible combinations of elements of the arrays given as parameters;
Pass each of them to the expression passed as first parameter;
Yield the result.

A particularly satisfying function will:

Avoid changing the value of any variable;
Be elegant;
Contain an inordinate amount of nested parenthesis/brackets;
Avoid foreach() loops.

Note that closures were introduced in PHP 5.3.0 .

I wasn't implying it was breaking news ^^

After all the pessimists and nihilists, now we have wannabilists!

First, a few neat things about list comprehensions, from a Haskell perspective:

The list monad in Haskell is set up so any list comprehension can be transformed into do notation rather easily:
> [(i,j) | i <- [1..3], j <- [1..3]]
[(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)]
> do {i <- [1..3]; j <- [1..3]; return (i,j)}
[(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)]

Haskell has a sequence function that takes a list of "actions" in a monad and returns a list of the results:
> sequence [getLine, getLine, getLine]
one
two
three
["one","two","three"]

Consequently, using sequence with the list monad gives you combinations for free:
> do {i <- [1..3]; j <- [1..3]; return [i,j]}
[[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]]
> sequence [[1..3], [1..3]]
[[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]]

Hence, the sequence function is very similar to the compr function asked for.  It just needs to be wrapped and mapped a bit:
function compr()
{
    $args = func_get_args();
    $f = $args[0];
    $call_f = function($array) use ($f) {
        return call_user_func_array($f, $array);
    };
    return array_map($call_f, sequence(listMonad(), array_slice($args, 1)));
}

Now, without further ado, here is a nearly direct translation of the list monad and sequence function from Haskell to PHP:
# instance  Monad []  where
#     m >>= k          = concat (map k m)
#     return x         = [x]
#     fail s           = []
function listMonad()
{
    return (object) array(
        'bind'   => function($m, $k) {
            return call_user_func_array('array_merge', array_map($k, $m));
        },
        'return' => function($x) { return array($x); },
        'fail'   => function($s) { return array(); }
    );
}

# sequence       :: Monad m => [m a] -> m [a]
# sequence       =  foldr mcons (return [])
#                     where mcons p q = p >>= \x -> q >>= \y -> return (x:y)
function sequence($monad, $list)
{
    $mcons =
        function($p, $q) use ($monad) {
            return call_user_func($monad->bind, $p,
                function($x) use ($monad, $q) {
                    return call_user_func($monad->bind, $q,
                        function($y) use ($monad, $x) {
                            return call_user_func($monad->return, cons($x, $y));});});};
    return foldr($mcons, call_user_func($monad->return, array()), $list);
}

# foldr            :: (a -> b -> b) -> b -> [a] -> b
# foldr f z []     =  z
# foldr f z (x:xs) =  f x (foldr f z xs)
function foldr($f, $z, $xs)
{
    if (empty($xs))
        return $z;
    return call_user_func($f, $xs[0], foldr($f, $z, array_slice($xs, 1)));
}

function cons($x, $xs)
{
    return array_merge(array($x), $xs);
}

I believe this meets all four of your criteria, especially the "inordinate amount of nested parenthesis/brackets" part.
Test code:
function printList($show, $list)
{
    echo showList($show, $list) . "\n";
}

function showList($show, $list)
{
    $str = "[";
    foreach($list as $x) {
        if ($str !== "[")
            $str .= ",";
        $str .= call_user_func($show, $x);
    }
    return $str . "]";
}

# Count in binary
printList('strval',
    compr(function($a, $b, $c, $d) {
        return "$a$b$c$d";
    }, array(0,1), array(0,1), array(0,1), array(0,1)));

# Combinations of items
printList(function($a) {return showList('strval', $a);},
    compr(function($a, $b, $c) {
        return array($a, $b, $c);
    }, array(1, 2), array(3, 4, 5), array(6, 7, 8, 9)));

Output:
[0000,0001,0010,0011,0100,0101,0110,0111,1000,1001,1010,1011,1100,1101,1110,1111]
[[1,3,6],[1,3,7],[1,3,8],[1,3,9],[1,4,6],[1,4,7],[1,4,8],[1,4,9],[1,5,6],[1,5,7],[1,5,8],[1,5,9],[2,3,6],[2,3,7],[2,3,8],[2,3,9],[2,4,6],[2,4,7],[2,4,8],[2,4,9],[2,5,6],[2,5,7],[2,5,8],[2,5,9]]

This is beautiful. You already had it or?

@cbrandolino: I hacked this up in a few hours.  However, it took me a long time to finally "get" how polymorphism is implemented in Haskell.  Namely, it eliminates type classes by turning contexts (e.g. (Monad m) => or (Show a) =>) into parameters.  I did this manually with the sequence and showList functions.  Once type classes are gone, type information can be erased.  Philip Wadler describes this in his talk Faith, Evolution, and Programming Languages .

Implemented using simple modulus/division.
function compr() {
    $args = func_get_args();
    $callback = array_shift($args);

    $total_length = array_product(array_map(function($arr) {
        return count($arr);
    }, $args));

    $return = array();
    for ($i = 0; $i < $total_length; $i++) {
        $params = array();
        $_i = $i;
        for ($j = 0; $j < count($args); $j++) {
            $base = count($args[$j]);
            $params[] = $args[$j][$_i % $base];
            $_i /= $base;
        }
        $return [] = call_user_func_array($callback, $params);
    }

    return $return;
}

Test:
$array = compr(function($a, $b, $c) {
    return $a + $b + $c;
}, array(1, 2), array(3, 4, 5), array(6, 7, 8, 9));

print_r($array);

Output:
Array
(
    [0] => 10
    [1] => 11
    [2] => 11
    [3] => 12
    [4] => 12
    [5] => 13
    [6] => 11
    [7] => 12
    [8] => 12
    [9] => 13
    [10] => 13
    [11] => 14
    [12] => 12
    [13] => 13
    [14] => 13
    [15] => 14
    [16] => 14
    [17] => 15
    [18] => 13
    [19] => 14
    [20] => 14
    [21] => 15
    [22] => 15
    [23] => 16
)

Nice! Still a bit too many liar variables and loops, but it looks pretty lightweight - at least if compared with the implementation I had in mind.

It can definitely be improved. I haven't refactored a single line after first getting it to work yet. Will update when I do.

source: Stack Exchange

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

sort: votes


text:
Sum of Fibonacci numbers
I found this task here.

Given the ith (1<=i<=35) Fibonacci
  number F(i) calculate the sum of the
  ith till i+9th number
  F(i)+F(i+1)+...+F(i+9) and the last
  digit of the i+246th one F(i+246)

I have been trying to solve this using python and some tricks(Binnet's formula and a tricky recurrence):
 f=lambda n:((1+5**.5)**n-(1-5**.5)**n)/(2**n*5**.5)
 exec"n=input();print int(55*f(n)+88*f(n+1)+f(n+6)%10);"*input()

but I didn't yet managed to squeeze thought the give source code limit which is 111 and mine is 115,any hints how to improve my solution?
I am a rather newbie to python so any sort of help resulting in a successful solution will be much appreciated.
Thanks,
PS:After posting the same question in stackoverflow I thought that this should be more appropriate here as this site is precisely for Puzzles and Codegolf.

Can you really not factor out 5**.5?

@Peter:Thanks,I missed that somehow :-(

Don't double post, if the mods on SO judge your question to be better suited for this site they will move it here.

As for golfing, you are doing it wrong, you don't need the fast formula, you need the short formula, and there is incidentally some extremely short formula to be found for this problem. Binet's is probably longer than the normal recurrence implementation, and if you really must use Binet's you can skip the -(1-5**.5)**n part and just round the result.

GolfScript 28 26 characters
Since the problem is here we might as well golf it. Anyone who plan on participating on spoj.pl better close their eyes while they read this.
~](;{11.@5+{.@+}*;.10%+n}%

It basically says: For all input, start with the numbers 11 and 11, do input+5 Fibonacci iterations, discard the highest of the two results, add itself mod 10 to the lowest result, done. As a formula this can be describes as 11*Fib(input+6) + (11*Fib(input+6)) mod 10.
Why does this work? It is simply a condensed way of calculating two second identities in the same run, one could start at [0 1] and [55 89], do a run on both of the same length and subtract the first result from the second to get the sum of a series of 10 Fibonacci numbers, but one may as well do the subtraction on the initial sets, thus getting the set [55 88], that can be stepped back a few steps to [11 11] which is short to write.
The Fibonacci series mod 10 has a period of 60, so Fib(i+246) mod 10 = Fib(i+6) mod 10.

Ehh could you please un-golf in English ?!

Description is reasonable, use ~] and n}% (or p}%) to save a couple more characters.

Thanks, now I wonder why I continue forgetting such simple stuff?

Accepted as you shown a very short procedure.

Python, 99 98 93 characters
F=[0,1]
exec'F+=[F[-2]+F[-1]];'*300
exec'G=F[input():];print sum(G[:10])+G[246]%10;'*input()

Could you please explain G=F[input():]? I can understand what it is doing but what I can't is how and why? Thanks,

It just takes the input (i) and grabs a slice of F starting at that input.  It is equivalent to doing i=input() then using F[i:i+10] and F[i+246], but a bit shorter.

If you use Binnet's formula+eBusiness idea you can reach 72 bytes python and with some crazy golfing even 62 bytes.

Perl, 78
sub F{$c=shift;$c>1?F($c-2)+F($c-1):$c}$_=<>;$x=F($_+11)-F($_+1);print$x+$x%10
This makes use of my observation that

the sum of F(i) to F(i+9) is equal to F(i+11) − F(i+1) — proof:
   F(i) + F(i+1) + F(i+2) + F(i+3) + F(i+4) + F(i+5) + F(i+6) + F(i+7) + F(i+8) + F(i+9)
=      F(i+2)    +     F(i+4)      +     F(i+6)      +     F(i+8)      +    F(i+10)
=      F(i+2)    - F(i+3) + F(i+5) +     F(i+6)      +     F(i+8)      +    F(i+10)
=           -F(i+1)       +      F(i+7)              +     F(i+8)      +    F(i+10)
=           -F(i+1)       +              F(i+9)                        +    F(i+10)
=           -F(i+1)       +                           F(i+11)

F(i+246) mod 10 is equal to (F(i+11) − F(i+1)) mod 10 (discovered by experimentation; no idea how to prove this)

User mohit would like to see that proof but can not yet comment.

@dmckee, @mohit: Added

05AB1E, 10 bytes
31Sb+ÅfÆ¤+

Port of @Timwi's Perl answer, so make sure to upvote him as well!
Try it online or verify the first \$[0,n]\$ test cases.
A straight-forward implementation would be 11 bytes instead:
9ÝƵ‘ª+Åf`θO

Try it online or verify the first \$[0,n]\$ test cases.
Explanation:
31S          # Push 31 as a list of digits: [3,1]
   b         # Convert both to a binary string: [11,1]
    +        # Add each to the (implicit) input-integer: [i+11,i+1]
     Åf      # Get the n'th Fibonacci number for each: [F(i+11),F(i+1)]
       Æ     # Reduce the pair by subtracting: F(i+11)-F(i+1)
        ¤    # Get its last digit (without popping)
         +   # And add it to the result
             # (after which it is output implicitly)

9Ý           # Push a list in the range [0,9]: [0,1,2,3,4,5,6,7,8,9]
  Ƶ‘         # Push compressed integer 246
    ª        # Append it to the list: [0,1,2,3,4,5,6,7,8,9,246]
     +       # Add each to the (implicit) input-integer:
             #  [i,i+1,i+2,i+3,i+4,i+5,i+6,i+7,i+8,i+9,i+246]
      Åf     # Get the n'th Fibonacci number for each
        `    # Pop the list, and push all values separated to the stack
         θ   # Pop the last number (the F(i+246)), and only leave its last digit
          O  # Sum all values on the stack
             # (after which the resulting sum is output implicitly)

See this 05AB1E tip of mine (section How to compress large integers?) to understand why Ƶ‘ is 246.

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/


text:
Artistic source code: Hello World
Back to basics! Create a "Hello World" program which prints, well, "Hello World". The winner this time though, is the one who gets the most interesting source code done. For instance, use obscure language features, make it obfuscated, or make the source code a peom or a piece of ASCII art. Your imagination and coding ability are the only limitations.

Print Hello World (exactly so)
Make sure your source code is... unique. Yeah, that.

To obey the FAQ, I can't just decide what I think is the best, thus the winner will be the one getting the most votes, and I will select an answer during the first day of May.

Between http://codegolf.stackexchange.com/questions/307/obfuscated-hello-world and http://codegolf.stackexchange.com/questions/1536/hello-world-0-0, we've seen chances to do this same work before, nor is the metric of the problem well defined.

@dmckee: This is a creativity challenge, thus it might occur as illdefined.

Every good question we have here is a creativity challenge. Every single one. You make think of that as a operational definition of a good contest.

@dmckee: Ok, sorry.

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


text:
What is the average of n, the closest prime to n, the square of n and the closest Fibonacci number to n?
This is a math problem which takes quite many things into question, making it rather challenging, and as you might have guessed, it's a code golf, so it should be as short as possible as well.
The input, \$n\$, is any integer number (should at least support integers, but needn't be limited to). The output is the average of:

\$n\$
The square of \$n\$, \$n^2\$
The closest prime number to \$n\$, \$p\$
The closest number to \$n\$ in the Fibonacci sequence, \$f\$

Shortly, the program should print to the standard output channel the result of $$\frac {n + n^2 + p + f} 4$$.
You don't have to care about possible overflows etc. Normal floating point precision is also ok.
The way the input is given is completely up to you. Shortest program (in characters) wins, as always with code golfs.
In the case a tie occurs when you are looking for the closest, choose one of the following:

Go up
Go down
Choose one randomly

Define "closest". How are ties broken?

@Peter Taylor: Move up, down, or choose one randomly.

Give some sample input/output to verify the solutions.

When you say “mustn't be limited to”, what else must be supported? Or did you mean “needn't be limited to”?

@Timwi! "needn't", sorry, will fix it

a) any integer includes, in my usage of the word, zero and numbers below zero. b) the first Fibonacci number is 1, isn't it? c) the first prime is 2 d) The next prime to two - do you consider it to be 2 or 3?

c'mon, let's get a Perl regex somewhere here!

Python 160 Chars
p=lambda n:any(n%x<1for x in range(2,n))
N=input()
a=0;b=1
while b<N:a,b=b,a+b
c=d=N
while p(c)and p(d):c-=1;d+=1
print (N+N*N+[b,a][2*N-a-b<0]+[c,d][p(c)])/4.0

A little explanation about the closestFib part:

When the while loop ends a is smaller
  than N and b is either equal to or
  greater than N. Now the
  [b,a][2*N-a-b<0] part. Look at it as
  [b,a][(N-a)-(b-N)]. (N-a) is the
  difference between N and a and
  similarly (b-N) the difference between
  b and N. If the difference between
  these two is less than 0 it means a is
  closer to N and vice-versa.

Could you add an explanation of why is this working?

@Debanjan Anything specific, you wan't to know? I thought everything was self explanatary. :)

Just the bit of nearest fib part [b,a][2*N-a-b<0] :)

GolfScript, 59 characters
~:N..*.,2>{:P{(.P\%}do(!},{{N-.*}$0=}:C~[1.{.@+.N<}do]C+++4/

This script does not fulfill some of the requirements:

It only works correctly for inputs n >= 2, otherwise it crashes.
The output is truncated to an integer.
Terrible performance for any moderately large n

A brief walkthrough of the code:

~:N..* The input is stored in N, and we push both n and the square n*n right away.
.,2> We will generate a list of primes by filtering the array [2..n*n]. We use our previous calculation of n*n as a (very bad!) upper bound for finding a prime that is larger than n.
{:P{(.P\%}do(!}, Our previous array is filtered by trial division. Each integer P is tested against every integer [P-1..1].
{{N-.*}$0=}:C~ Sorts the previous array based on the distance to n, and grabs the first element. Now we have the closest prime.
[1.{.@+.N<}do]C We generate Fibonnacis until we get one greater than n. Fortunately, this algorithm naturally keeps track of the previous Fibonnaci, so we throw them both in an array and use our earlier distance sort. Now we have the closest Fibonnaci.
+++4/ Average. Note that GolfScript doesn't have support for floats, so the result is truncated.

GolfScript, 81 characters
Here is a variant that fulfills all of the requirements.
~:N..*2N*,3,|2,^{:P{(.P\%}do(!},{{N-.*}$0=}:C~[0.1{.@+.N<}do]C+++100:E*4/.E/'.'@E%

To ensure proper behavior for n<2, I avoid 2< (crashes when the array is small), and instead use 3,|2,^. This makes sure the prime candidate array is just [2] when n < 2. I changed the upper bound for the next prime from n*n to 2*n (Bertrand's postulate). Also, 0 is considered a Fibonnaci number. The result is calculated in fixed point math at the end. Interestingly, it seems like the result is always in fourths (0, .25, .5, .75), so I hope 2 decimal places of precision is sufficient.
My first crack at using GolfScript, I'm sure there is room for improvement!

You know, when dividing by 4 it's not terribly surprising you get fourths ;-)

...indeed! +1 ;)

JavaScript, 190
function n(n)
{z=i(n)?n:0
for(x=y=n;!z;x--,y++)z=i(x)?x:i(y)?y:0
for(a=b=1;b<n;c=a+b,a=b,b=c);
return(n+n*n+(2*n-a-b<0?a:b)+z)/4}
function i(n)
{for(j=2;j<n;j++)
if(!(n%j))return 0
return 1}

[257]
function n(n)
{return(n+n*n+p(n)+f(n))/4}
function p(n)
{if(i(n))return n
for(a=b=n;;a--,b++){if(i(a))return a
if(i(b))return b}}
function i(n)
{for(j=2;j<n;j++)
if(!(n%j))return 0
return 1}
function f(n)
{for(a=b=1;b<n;c=a+b,a=b,b=c);
return 2*n-a-b<0?a:b}

Uncompressed:
function closest( a, b, c )
{
  return 2*a-b-c < 0 ? b : c;
}

function closestPrime( n )
{
  a=b=n;
  if (isPrime( n ) ) return n;
  while ( true )
  {
    a-=1;
    b+=1;
    if (isPrime(a))return a;
    if (isPrime(b))return b;
  }
}

function isPrime( n )
{
  for (i=2;i<n;i++)
  {
    if ( !( n % i ) ) return false;
  }
  return true;
}

function closestFib( n )
{
  for(fib1=0,fib2=1;fib2<n;fib3=fib1+fib2,fib1=fib2,fib2=fib3);
  return closest( n, fib1, fib2 );
}

function navg(n)
{
  n2 = n*n;
  np = closestPrime( n );
  nf = closestFib( n );
  return ( n + n2 + np + nf ) / 4;
}

For your closest prime function: I'm thinking you can save space if you use just a=0 and increment positively.  Instead of checking isPrime for a and b, just check isPrime(n+a) and isPrime(n-a).  You could probably mash it all into one crazy ternary statement, but I'm terrible with javascript.

The following seems to work pretty well: function closestPrime(n,o){return isPrime(n+o)?n+o:isPrime(n-o)?n-o:closestPrime(n,o+1);}.  Call it as closestPrime(n,0) and it'll work itself out.  Shorten as needed.

Mathematica, 70 69 bytes
One byte saved thanks to Sp3000 (sometimes built-ins aren't the best way to go).
((n=#)+#^2+(f=#&@@#@Range@Max[1,2n]~Nearest~n&)@Prime+f@Fibonacci)/4&

This defines an unnamed function taking an integer and producing the exact mean as a rational number. In the case of ties, the smaller prime/Fibonacci number is chosen.
This is very inefficient for large inputs, because it actually generates the first 2n primes and Fibonacci numbers before picking the closest.

#&@@# .. Huh?

@Sieg Starting from the right: # is the argument of a pure function (of f). This case, it's actually a function itself, since f is applied to Prime and Fibonacci. So that #@Range@... applies the given function to each integer in the range. Then #&@@ is just a golfed way to extract the first element of a list. It works by applying #& to the list, which is a function which merely returns its first argument.

Vyxal, 18 15 bytes
₌∆p²?:ɾ∆f‡?ε∵Wṁ

-3 bytes thanks to emanresu A
Try it online!
Explanation:
₌                # Parallel apply:
 ∆p              #   Nearest prime
   ²             #   Square
    ?            # Push the input
     :           # Duplicate
      ɾ          # Range from 0 to n
       ∆f        # Nth fibonacci number
            ∵    # Minimum by:
         ‡       # A two element lambda that gets
           ε     #   The absolute difference of it's input
          ?      #   And the program's input
              ṁ  # Mean of
             W   # The stack

15 (d-updot is for decimal output, not necessary)

@emanresuA Thanks, I'm stupid lol

Q, 119
Not the most efficient.
{%[;4]x+(x*x)+((*:)a(&)b=min b:abs x-a:{x,sum -2#x}/[x-2;1 1])+(*:)d(&)e=min e:x-d:(&)1={(min x mod 2_(!)x)}each(!)x+2}

MATLAB 88 Chars
C=@(F)(F(abs(F-n)==min(abs(F-n))));(n+n^2+C(primes(n*2))+C(round(1.618.^(1:n)/2.236)))/4

n is your integer
Works with non integers, as far as I've tested it works with very large numbers as well, runs pretty damn quickly too.

Scala 299
object F extends App{type I=Int
def f(n:I,b:I=1,a:I=1):I=if(a>=n)if(a-n>n-b)b else a else f(n,a,b+a)
def p(n:I)=(2 to n-1).exists(n%_==0)
def i(n:I,v:I):Int=if(!p(n+v))n+v else i(n+v,v)
val a=readInt
println(({val p=Seq(-1,1).map(i(math.max(a,3),_))
if(a-p(0)>p(1)-a)p(1)else p(0)}+f(a)+a+a*a)/4.0)}

Test and invocation:
a  a² nP(a) nF  ∑   /4.0
------------------------
-2  4   2   1   5   1.25
-1  1   2   1   3   0.75
0   0   2   1   3   0.75
1   1   2   1   5   1.25
2   4   2   2   10  2.5
3   9   2   3   17  4.25
4   16  3   5   28  7.0
5   25  3   5   38  9.5

The question talks about any Integer but the problem isn't that interesting for values below 0. However - how do we start? At 0? At 1? And what is the next prime for 11? 11 itself?
The idea to allow the next bigger or lower in case of a tie is bad, because it makes comparing needless difficult. If your results differ, they can have chosen the other fib, the other prime, the other fib and the other prime, or yours are wrong, or the result of the other person is wrong, or it is a combination: different choice, but wrong although, maybe both wrong.

Jelly, 19 bytes
ÆnÆRạÞ+ÆḞ€ạÞ$Ḣ++²÷4

Try it online!
How it works
ÆnÆRạÞ+ÆḞ€ạÞ$Ḣ++²÷4 - Main link. Takes N on the left
Æn                  - Get the next prime after N
  ÆR                - Primes up to this
     Þ              - Sort by:
    ạ               -   Absolute difference with N
                      This moves the smallest, closest prime to N to the front, p

            $       - Last 2 links as a monad f(N):
         €          -   For each 1 ≤ i ≤ N:
       ÆḞ           -     Get the ith Fibonacci number
          ạÞ        -   Sort by abs diff with N
                      This moves the smallest, closest Fib to N to the front, f

      +             - Add element-wise. The first element will be p+f
             Ḣ      - Extract p+f
              +     - Add N
                ²   - N²
               +    - Add N². We now have N+N²+p+f
                 ÷4 - Divide by 4

Haskell, 150 bytes
import Data.List
f n=print$let q=head.sortOn(abs.(n-)).take(1+n^2);z=1:zipWith(+)z(1:z)in(read$show$q[p|p<-[2..],all((>0).mod p)[2..p-1]]+q z+n+n^2)/4

Try it online!

Japt, 24 bytes
+²+UÆMgXÃñaU Î+_j}c+U)*¼

Try it

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

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


text:
Find the prime factors
In this task, you have to write a program, that computes the prime factors of a number. The input is a natural number 1 < n < 2^32. The output is a list of the prime factors of the number in the following format. Exponents must be omitted if they are 1. Only output prime numbers. (Assuming the input is 131784):

131784 = 2^3 * 3 * 17^2 * 19

Using the same amount of whitespace is not required; whitespace may be inserted wherever appropriate. Your program should complete in less then 10 minutes for any input. The program with the shortest amount of characters wins.

Bonus points if your program can factor 6857599914349403977654744967172758179904114264612947326127169976133296980951450542789808884504301075550786464802304019795402754670660318614966266413770127 in less than 73 days!

@Joey Adams: The factorization starts out with 1771113997313597...

@FUZxxl: I think you made a mistake copying the number.  It's the product of two large primes.

@Joey Can we use Shor's Algorithm?

@muntoo: Do you have the hardware to test it?  :-)

@Joey I accidentally spilled some coffee over my quantum computer, and my friend is using his to "hack into the US Government" or something unimportant, so, no. :(

What, no CJam yet?

@IngoBürk 18 chars: rimF{1-'^*}%" * "* and indeed it doesn't qualify

SageMath, 31 Bytes
N=input()
print N,"=",factor(N)

Test case:
83891573479027823458394579234582347590825792034579235923475902312344444
Outputs:
83891573479027823458394579234582347590825792034579235923475902312344444 = 2^2 * 3^2 * 89395597 * 98966790508447596609239 * 263396636003096040031295425789508274613

Congrats on winning a challenge with your very first post, nice work! And welcome to the site!

Ruby 1.9, 74 70 characters
#!ruby -plrmathn
$_+=?=+$_.to_i.prime_division.map{|a|a[0,a[1]]*?^}*?*

Edits:

(74 -> 70) Just use the exponent as slice length instead of explicitly checking for exponent > 1

Perl 5.10, 73 88
perl -pe '$_=`factor $_`;s%( \d+)\K\1+%-1-length($&)/length$1%ge;y, -,*^,;s;\D+;=;'

Takes input number from standard input.  Will compute factors for multiple inputs if provided.
Counted as a difference to perl -e.  5.10 is needed for the \K regex metacharacter.

+1 for using factor.

Shouldn't you count the  p option?

@Joey indeed I should.  Sorry about that. Fixing.

Haven’t tested this, but instead of split/\D/,~factor $_~;$_="@_"; could you write $_=~factor $_~;s/\D/ /g;? (Of course replace ~ with the backtick.)

You mean $_=`factor $_`;s/\D/ /g;? Dual backtick encasing helps.

@Timwi it wouldn't have worked because I used split's feature of not yielding a trailing empty string, resulting in the absence of whitespace at end of string.  Then again, by not performing the transformation at all, I can keep the newline and have the rest work just fine, so I simplified all that.

Python, 140 135 133 chars
M=N=input()
s=''
f=1
while f<4**8:
 f+=1;e=0
 while N%f<1:e+=1;N/=f
 if e:s+='*%d'%f+'^%d'%e*(e>1)
print M,'=',(s+'*%d'%N*(N>1))[1:]

I think the output requires some more spaces, e.g. ' * %d'... And two more things: 65536 == 4**8; Line 7: if e:s+='*%d'%f+'^%d'%e*(e>1)

@BlaXpirit: "same amount of whitespace is not required".  Thanks for the other two, I'll incorporate them.

J, 72
(":*/f),'=',([,'*',])/(":"0~.f),.(('^',":)`(''"0)@.(=&1))"0+/(=/~.)f=.q:161784

Typical J.  Two characters to do most of the work, sixty characters to present it.
Edit: Fixed the character count.

This doesn't look like 62 characters to me. Even when assuming 161784 is your input, it's still 72 characters.

Wouldn't it be shorter with |: __ q: y?

@Ventero: typical JB.  Two hours to golf the damned thing, fifteen seconds to mess up the character count.

OCaml, 201 characters
A direct imperative translation of the best Python code:
let(%)s d=if!d>1then Printf.printf"%s%d"s!d
let f n=let x,d,e,s=ref n,ref 1,ref 0,ref"="in""%x;while!d<65536do
incr d;e:=0;while!x mod!d=0do x:=!x/ !d;incr e
done;if!e>0then(!s%d;"^"%e;s:="*")done;!s%x

For example,
# f 4294967292;;
4294967292=2^2*3^2*7*11*31*151*331- : unit = ()

(note that I've omitted outputting the final endline.) Just for fun, at 213 characters, a purely functional version, thoroughly obfuscated through liberal use of operators:
let(%)s d=if d>1then Printf.printf"%s%d"s d
let f x=let s=ref"="in""%x;let rec(@)x d=if d=65536then!s%x else
let rec(^)x e=if x/d*d<x then x,e else x/d^e+1in
let x,e=x^0in if e>0then(!s%d;"^"%e;s:="*");x@d+1in x@2

J, 53 52 characters
This solution takes the rplc trick from the solution of randomra but comes up with some original ideas, too.
":,'=',(":@{.,'^','*',~":@#)/.~@q:}:@rplc'^1*';'*'"_

In non-tacit notation, this function becomes
f =: 3 : 0
(": y) , '=' , }: (g/.~ q: y) rplc '^1*' ; '*'
)

where g is defined as
g =: 3 : 0
": {. y) , '^' , (": # y) , '*'
)

q: y is the vector of prime factors of y. For instance, q: 60 yields 2 2 3 5.
x u/. y applies u to y keyed by x, that is, u is applied to vectors of elements of y for which the entries in x are equal. This is a bit complex to explain, but in the special case y u/. y or u/.~ y, u is applied to each vector of distinct elements in y, where each element is repeated for as often as it appears in y. For instance, </.~ 1 2 1 2 3 1 2 2 3 yields
┌─────┬───────┬───┐
│1 1 1│2 2 2 2│3 3│
└─────┴───────┴───┘

# y is the tally of y, that is, the number of items iny.
": y formats y as a string.
x , y appends x and y.
{. y is the head y, that is, its first item.
Thus, (": {. y), '^' , (": # y) , '*' formats a vector of n repetitions of a number k into a string of the form k ^ n *. This phrase in tacit notation is :@{.,'^','*',~":@#, which we pass to the adverb /. described further above.
x rplc y is the library function replace characters. y has the form a ; b and every instance of string a in x is replaced by b. x is ravelled (that is, reshaped such that it has rank 1) before operation takes place, which is used here. This code replaces ^1* with * as to comply with the mandated output format.
}: y is the curtail of y, that is, all but its last item. This is used to remove the trailing *.

Couldn't you save a lot of work by using __ q:? Try it online!

@Adám Indeed, good idea!

PHP, 112
echo$n=$_GET[0],'=';$c=0;for($i=2;;){if($n%$i<1){$c++;$n/=$i;}else{if($c){echo"$i^$c*";}$c=0;if(++$i>$n)break;}}

118
echo $n=$_GET[0],'=';for($i=2;;){if(!($n%$i)){++$a[$i];$n/=$i;}else{if($a[$i])echo "$i^$a[$i]*";$i++;if($i>$n)break;}}

JavaScript, 124 122 119
for(s='',i=2,o=p=prompt();i<o;i++){for(n=0;!(p%i);n++)p/=i;n?s+=i+(n-1?'^'+n:'')+'*':0}alert(s.substring(0,s.length-1))

Python 119 Chars
M=N=input()
i=1
s=""
while N>1:
 i+=1;c=0
 while N%i<1:c+=1;N/=i
 if c:s+=" * %d"%i+['','^%d'%c][c>1]
print M,'=',s[3:]

That's what I tried first, but it is too slow for big primes, like 4294967291.

@Keith The question allows upto 10 minutes. Will this take more than 10 minutes for the worst case?

It took 32 minutes on my machine for that number.

Perl, 78
use ntheory":all";say join" * ",map{(join"^",@$_)=~s/\^1$//r}factor_exp(shift)

It uses the s///r feature of Perl 5.14 to elide the ^1s.  81 characters to run in a loop:
perl -Mntheory=:all -nE 'chomp;say join" * ",map{(join"^",@$_)=~s/\^1$//r}factor_exp($_);'

You can leave out the spaces if you like. This would save two characters. Nice solution!

PHP, 236 characters
$f[$n=$c=$argv[1]]++;echo"$n=";while($c){$c=0;foreach($f as$k=>$n)for($r=~~($k/2);$r>1;$r--){if($k%$r==0){unset($f[$k]);$f[$r]++;$f[$k/$r]++;$c=1;break;}}}foreach($f as$k=>$n)if(--$n)$f[$k]="$k^".++$n;else$f[$k]=$k;echo implode("*",$f);

Output for 131784: 2^3*3*17^2*19
Completes all numbers within a few seconds while testing.
4294967296=2^32
Time: 0.000168

Input was never specified, so I chose to call it using command line arguments.
php factorize.php 4294967296

Scala 374:
def f(i:Int,c:Int=2):List[Int]=if(i==c)List(i)else
if(i%c==0)c::f(i/c,c)else f(i,c+1)
val r=f(readInt)
class A(val v:Int,val c:Int,val l:List[(Int,Int)])
def g(a:A,i:Int)=if(a.v==i)new A(a.v,a.c+1,a.l)else new A(i,1,(a.v,a.c)::a.l)
val a=(new A(r.head,1,Nil:List[(Int,Int)])/:(r.tail:+0))((a,i)=>g(a,i))
a.l.map(p=>if(p._2==1)p._1 else p._1+"^"+p._2).mkString("", "*", "")

ungolfed:
def factorize (i: Int, c: Int = 2) : List [Int] = {
  if (i == c) List (i) else
    if (i % c == 0) c :: f (i/c, c) else
      f (i, c+1)
}
val r = factorize (readInt)
class A (val value: Int, val count: Int, val list: List [(Int, Int)])
def g (a: A, i: Int) =
  if (a.value == i)
    new A (a.value, a.count + 1, a.list) else
    new A (i, 1, (a.value, a.count) :: a.list)
val a = (new A (r.head, 1, Nil: List[(Int,Int)]) /: (r.tail :+ 0)) ((a, i) => g (a, i))
a.l.map (p => if (p._2 == 1) p._1 else
  p._1 + "^" + p._2).mkString ("", "*", "")

J, 74 chars
f=.3 :0
(":y),'=',' '-.~('^1 ';'')rplc~}:,,&' *'"1(,'^'&,)&":/"{|:__ q:y
)

   f 131784
131784=2^3*3*17^2*19

64 chars with input in variable x:
   x=.131784

   (":x),'=',' '-.~('^1 ';'')rplc~}:,,&' *'"1(,'^'&,)&":/"{|:__ q:x
131784=2^3*3*17^2*19

If you manage to turn this into a tacit definition, you can avoid escaping all the quotes. You could also use a 3 : 0 defintion.

@FUZxxl I expected I can just put in the unescaped string in  the 3 : 0 version but it didn't work somewhy. I might try tacit later though. This is the 3:0 I tried: http://pastebin.com/rmTVAk4j.

It should work. I don't see why. Did you name your argument y as you are supposed to?

@FUZxxl This is the 3:0 I tried: http://pastebin.com/rmTVAk4j.

The 3:0 you tried doesn't exactly match the one-liner you provide. It uses '' instead of a: in one place. Maybe that's the difference?

@FUZxxl I just changed '' to a: to decrease escaping.

I tried this and it worked. I don't know where your problem is.

@FUZxxl Thanks, now it works. No idea what was the problem.

Thank you for the rplc trick. I incorporated it into my solution.

Couldn't you save a lot of work by using __ q:? Try it online!

@Adám that is the first (rightmost) step in the code: ´__ q:x´

Java 10, 109 108 bytes (lambda function)
n->{var r=n+"=";for(int i=1,f;i++<n;r+=f<1?"":(f<2?i:i+"^"+f)+(n>1?"*":""))for(f=0;n%i<1;n/=i)f++;return r;}

Try it online.
Java 6+, 181 bytes (full program)
class M{public static void main(String[]a){long n=new Long(a[0]),i=1,f;String r=n+"=";for(;i++<n;r+=f<1?"":(f<2?i:i+"^"+f)+(n>1?"*":""))for(f=0;n%i<1;n/=i)f++;System.out.print(r);}}

Try it online.
-1 byte thanks to @ceilingcat.
Explanation:
n->{                // Method with integer parameter and String return-type
  var r=n+"=";      //  Result-String, starting at the input with an appended "="
  for(int i=1,f;i++<n;
                    //  Loop in the range [2, n]
      r+=           //    After every iteration: append the following to the result-String:
        f<1?        //     If the factor `f` is 0:
         ""         //      Append nothing
        :           //     Else:
         (f<2?      //      If the factor `f` is 1:
           i        //       Append the current prime `i`
          :         //      Else:
           i+"^"+f) //       Append the current prime `i` with it's factor `f`
         +(n>1?     //      And if we're not done yet:
            "*"     //       Also append a "*"
           :        //      Else:
            ""))    //       Append nothing more
    for(f=0;        //   Reset the factor `f` to 0
        n%i<1;      //   Loop as long as `n` is divisible by `i`
      n/=i)         //    Divide `n` by `i`
      f++;          //    Increase the factor `f` by 1
  return r;}        //  Return the result-String

Japt, 28 27 26 bytes
-1 byte thanks to Shaggy
+'=+Uk ü ®ÊÉ?ZÌ+'^+Zl:ZÃq*

Try it

Disqualified as your language was created after this task was published.

@FUZxxl Using a newer language on an older challenge is allowed

It was not allowed back when the challenge was posted.  I consider it to be unfair to amend the rules of a challenge after the challenge has been posted, so languages published after this challenge remain illegal.

@FUZxxl You don't have to accept my answer, but I am allowed to answer it regardless.

indeed you are!

24 bytes

Wait, crap, no; that'll fail for the likes of 2048.

Jelly, 16 bytes
³”=³ÆFḟ€1j€”^j”*

One of my first Jelly answers, so can definitely be golfed (especially ³”=³)..
Try it online.
Explanation:
³                 # Push the first argument
 ”=               # Push string "="
   ³ÆF            # Get the prime factor-exponent pairs of the first argument
      ḟ€1         # Remove all 1s from each pair
         j€”^     # Join each pair by "^"
             j”*  # Join the pair of strings by "*"
                  # (implicitly join the entire 'stack' together)
                  # (which is output implicitly as result)

Powershell, 113 97 bytes
Inspired by Joey's answer. It's a slow but short.
param($x)(2..$x|%{for(;!($x%$_)){$_
$x/=$_}}|group|%{$_.Name+"^"+$_.Count-replace'\^1$'})-join'*'

Explained test script:
$f = {

param($x)               # let $x stores a input number > 0
(2..$x|%{               # loop from 2 to initial input number
    for(;!($x%$_)){     # loop while remainder is 0
        $_              # push a current value to a pipe
        $x/=$_          # let $x is $x/$_ (new $x uses in for condition only)
    }
}|group|%{              # group all values
    $_.Name+"^"+$_.Count-replace'\^1$'  # format and remove last ^1
})-join'*'              # make string with *

}

&$f 2
&$f 126
&$f 129
&$f 86240
#&$f 7775460

Output:
2
2*3^2*7
3*43
2^5*5*7^2*11

05AB1E, 22 20 bytes
ÐfsÓ0Køε1K'^ý}'*ý'=ý

-2 bytes thanks to @Emigna.
Try it online.
Explanation:
Ð                # Triplicate the (implicit) input-integer
 f               # Pop and push all prime factors (without counting duplicates)
  s              # Swap to take the input again
   Ó             # Get all prime exponents
    0K           # Remove all 0s from the exponents list
      ø          # Zip it with the prime factors, creating pairs
       ε         # Map each pair to:
        1K       #  Remove all 1s from the pair
        '^ý     '#  And then join by "^"
       }'*ý     '# After the map: join the string/integers by "*"
           '=ý  '# And join the stack by "=" (with the input we triplicated at the start)
                 # (after which the result is output implicitly)

1K should work instead of `≠iy in the loop.

@Emigna Ah lol.. I actually do that in my Jelly answer I just posted. Not sure why I didn't think of it earlier here. :)

APL(NARS), 66 chars, 132 bytes
{(⍕⍵),'=',3↓∊{m←' * ',⍕↑⍵⋄1=w←2⊃⍵:m⋄m,'^',⍕w}¨v,¨+/¨{k=⍵}¨v←∪k←π⍵}

test and comment:
  f←{(⍕⍵),'=',3↓∊{m←' * ',⍕↑⍵⋄1=w←2⊃⍵:m⋄m,'^',⍕w}¨v,¨+/¨{k=⍵}¨v←∪k←π⍵}
  f 131784
131784=2^3 * 3 * 17^2 * 19
  f 2
2=2
  f (2*32)
4294967296=2^32

{(⍕⍵),'=',3↓∊{m←' * ',⍕↑⍵⋄1=w←2⊃⍵:m⋄m,'^',⍕w}¨v,¨+/¨{k=⍵}¨v←∪k←π⍵}
k←π⍵      find the factors with repetition of ⍵ and assign that array to k example for 12 k is 2 2 3
v←∪       gets from k unique elements and put them in array v
+/¨{k=⍵}¨ for each element of v count how many time it appear in k (it is array exponents)
v,¨       make array of couples from element of v (factors unique) and the array above (exponents unique)
∊{m←' * ',⍕↑⍵⋄1=w←2⊃⍵:m⋄m,'^',⍕w}¨ pretty print the array of couples factor exponent as array chars
3↓                                 but not the first 3 chars
(⍕⍵),'='  but print first the argument and '=' in char format

if someone has many time with these primitives, know them very well them, for me it is possible that
the code is clearer of comments... so code more clear than comments, comments unuseful...

QBasic, 156 characters
INPUT n#
?n#;"=";
f=2
1c=0
WHILE n#/f=INT(n#/f)
n#=n#/f
c=c+1
WEND
IF c THEN?f;
IF c>1THEN?"^";c;
IF c*(n#>1)THEN?"*";
f=f+1
IF f*f<=n#GOTO 1
IF n#>1THEN?n#

When run at Archive.org, this takes about 2½ minutes to finish for an input of 4294967291, the largest prime in the specified range.
Ungolfed, with some remarks
This is the version I used to get the timing information:
CLS
INPUT num#
PRINT num#; "=";
factor = 2

startTime# = TIMER

DO
    count = 0
    WHILE num# / factor = INT(num# / factor)
        num# = num# / factor
        count = count + 1
    WEND
    IF count > 0 THEN PRINT factor;
    IF count > 1 THEN PRINT "^"; count;
    IF count > 0 AND num# > 1 THEN PRINT "*";
    factor = factor + 1
LOOP WHILE factor * factor <= num#

IF n# > 1 THEN PRINT n# ELSE PRINT

time# = TIMER - startTime#
PRINT "Search took"; INT(time# / 60); "minutes and";
PRINT INT(time# mod 60); "seconds"

The program uses the standard approach of trial division of each factor between \$2\$ and \$\sqrt n\$. It prints a * after each successful factor if the remaining \$n\$ is still greater than 1. If the factor becomes greater than \$\sqrt n\$ while \$n > 1\$, then \$n\$ is prime and we output it after exiting the loop.
A few extra bytes had to be spent to cope with very large numbers:
QBasic's numbers are either single- or double-precision floating point under the hood, although it casts to integers for certain calculations. Integers greater than \$2^{24}\$ are not guaranteed to be accurately represented in single-precision floating point, so we have to use double-precision for \$n\$ (thus the double-precision sigil on the variable num#). However, since we're only checking factors up to \$\sqrt n < 2^{16}\$, we can use the default single precision for factor.
At first, I had WHILE num# MOD factor = 0 for the inner loop. This worked until I tried numbers close to \$2^{32}\$, at which point it said "Overflow." It seems that the MOD operator casts its operands to integers--specifically, 32-bit signed integers. A value of \$2^{32}-1\$ can fit in a 32-bit unsigned integer, but not a signed one. So MOD wasn't going to work. Neither was my usual golf trick of checking divisibility with a/b=a\b, since the int-div operator \ also casts to integers. Fortunately, I could still use floating point division and then truncate explicitly with the INT function (which seemingly does not cast to integer--??).
Given the issues with single- vs. double-precision, I assumed that squaring factor (single-precision) before comparing it with num# (double) wasn't going to work. But surprisingly, it did. My best guess after some experimentation is that if there's a double-precision value anywhere in an expression, QBasic casts all of the values to double before computing anything. This contrasts with C, for example, where implicit casting only occurs between the operands of a single operator.

JavaScript, 107
n=prompt()
s=n+'='
c=0
for(i=2;;){if(n%i<1){c++
n/=i}else{if(c)s+=i+'^'+c+'*'
c=0
if(++i>n)break}}
alert(s)

120
n=prompt()
o={2:0}
for(i=2,c=n;i<=c;)!(c%i)?++o[i]?c/=i:0:o[++i]=0
s=n+'='
for(i in o)s+=o[i]?i+'^'+o[i]+'*':''
alert(s)

Has a trailing * in the output and prints the exponent even if it's 1.

no need to downvote. There's nowhere that said that it couldn't print the exponent if it's 1. Also, the trailing * assumes multiplying by 1. If it's that big an issue, I'll fix it.

»in the following format« in the task description pretty much implies that an exponent of 1 should not be printed. And no, a trailing  * is also against that. If one could choose the output format that freely, then shelling out to factor(1) would be the easiest one. Answers can only reasonably compared if they all solve the same problem.

As the creator of this task, I say, that the exponents have to be omitted if 1 and only prime-numbers can be factors.

PHP, 112 bytes
<?=$a=$argn,"=";for($i=2;1<$a;)$a%$i?$i++:$a/=$i+!++$r[$i];foreach($r as$k=>$v)echo$t?"*":!++$t,$v<2?$k:"$k^$v";

Try it online!

PHP, 93 bytes
<?=$n=$argn;for($i=2;$n>1;$k&&$p=print($p?"*":"=")."$i^$k",$i++)for($k=0;$n%$i<1;$n/=$i)$k++;

I could do 89 bytes with PHP 5.5 (or later), but that postdates the challenge by more than 2 years:
<?=$n=$argn;for($i=2;$n>1;$k&&$p=print"=*"[$p]."$i^$k",$i++)for($k=0;$n%$i<1;$n/=$i)$k++;

Run as pipe with -nF or try them online.

Japt, 24 bytes
+'=+Uk ü ËÎ+DÅÊÎç^+DÊÃq*

Try it

Go, 199 bytes
type M=map[int]int
func f(n int)M{m:=make(M)
for x,i:=n,2;i<=n;i++{if func(p int)int{if p<4{return p}else{for i:=2;i*i<=p;i+=2{if p%i==0{return-1}}}
return p}(i)>0{for x%i==0{m[i]++;x/=i}}}
return m}

Attempt This Online!
Returns a map where the keys are the bases, and the values are exponents. So 131784 => map[2:3 3:1 17:2 19:1]


text:
Ascii art equation visualizer
Dealing with equations in the absence of a good equation editor is messy and unpleasant. For example, if I wanted to express an integral and its solution, it might look something like this:
Integral[x^3 e^(-m x^2 b /2), dx] =
-((2 + bmx^2)/(b^2*e^((bmx^2)/2)*m^2))
At integrals.wolfram.com, this is called "input form." No one likes to see an equation in "input form." The ideal way of visualizing this equation would be:

(Wolfram calls this "traditional form")
For this codegolf, write a program that will take some equation in "input form" as input and visualize that equation in an ascii representation of "traditional form." So, for this example we might get something like this:
       /\      3
       |      x
       | ------------  dx =
       |       2
      \/   (m x  b)/2
          e

              2
     2 + b m x
-(-----------------)
            2
   2  (b m x )/2  2
  b  e           m

Requirements:

Don't shuffle, simplify or
rearrange the input in any way. Render it
in exactly the same form it was described by the input.
Support the four basic
mathematical operations (+,-,*,/). When not multiplying two adjacent numbers the * symbol is implied and should be omitted.
Support for integration (as shown in the
example above) is not required. Being able to support input with functions like Integrate[...] or Sqrt[...] is a bonus.
Support powers as
shown in the example above (the nth root can be modeled by raising to the 1/nth power).
Redundant parenthesis (like those around the denomentator and numerator of the large fraction in the example above) should be omitted.
The expression in the denominator and numerator of a fraction should be centered above and below the horizontal division line.
You can choose whether or not to start a new line after an equal sign. In the example above, a new line is started.
Order of operations must be exactly the same in the output as it is in the input.

Some examples of input and associated output for testing your solution:
Input:
1/2 + 1/3 + 1/4

Output:
1   1   1
- + - + -
2   3   4

Input:
3x^2 / 2 + x^3^3

Output:
   2     3
3 x     3
---- + x
 2

Input:
(2 / x) / (5 / 4^2)

Output:
2
-
x
--
5
--
 2
4

Input:
(3x^2)^(1/2)

Output:
    2 1/2
(3 x )

Your question should generally have a tag expressing what kind of contest it is. I've taken the liberty of adding one because you said "codegolf" in the text.

This problem is too nebulous to be code-golf. You don't say what constructs must be supported, or what they have to look like. Would just supporting +, -, *, and / be enough? Does Sigma have to be supported? What about greek letters? The possible solutions to the question as you've posed it could be too varied in functionality to be compared for code-length.

@MtnViewMark, I added some "Requirements"...let me know if the golf is better now.

@Ami - yes, much.

I agree with MtnViewMark, this seems very open ended and vague. Perhaps you would be better to limit the input and output to a well defined set of testcases for the purposes of golfing. Have you done a reference implementation?

@gnibbler do the test cases I provided help? I am working on a reference implementation.

Won't the output of (2 / x) / (5 / 4^2) be interpreted as 2 / x / 5 / 4^2 which is not the same?

@mellamokb, I don't care about that ambiguity because the same ambiguity would exist for the "traditional form" of the equation as displayed by an equation editor.

Python 2, 1666 chars
The layout is actually pretty easy - it's the parsing of the input that's a royal pain.  I'm still not sure it is completely correct.
import re,shlex
s=' '
R=range

# Tokenize.  The regex is because shlex doesn't treat 3x and x3 as two separate tokens.  The regex jams a space in between.
r=r'\1 \2'
f=re.sub
x=shlex.shlex(f('([^\d])(\d)',r,f('(\d)([^\d])',r,raw_input())))
T=[s]
while T[-1]:T+=[x.get_token()]
T[-1]=s

# convert implicit * to explicit *
i=1
while T[i:]:
 if(T[i-1].isalnum()or T[i-1]in')]')and(T[i].isalnum()or T[i]in'('):T=T[:i]+['*']+T[i:]
 i+=1

# detect unary -, replace with !
for i in R(len(T)):
 if T[i]=='-'and T[i-1]in'=+-*/^![( ':T[i]='!'
print T

# parse expression: returns tuple of op and args (if any)
B={'=':1,',':2,'+':3,'-':3,'*':4,'/':4,'^':5}
def P(t):
 d,m=0,9
 for i in R(len(t)):
  c=t[i];d+=c in'([';d-=c in')]'
  if d==0and c in B and(B[c]<m or m==B[c]and'^'!=c):m=B[c];r=(c,P(t[:i]),P(t[i+1:]))
 if m<9:return r
 if'!'==t[0]:return('!',P(t[1:]))
 if'('==t[0]:return P(t[1:-1])
 if'I'==t[0][0]:return('I',P(t[2:-1]))
 return(t[0],)

# parenthesize a layout
def S(x):
 A,a,b,c=x
 if b>1:A=['/'+A[0]+'\\']+['|'+A[i]+'|'for i in R(1,b-1)]+['\\'+A[-1]+'/']
 else:A=['('+A[0]+')']
 return[A,a+2,b,c]

# layout a parsed expression.  Returns array of strings (one for each line), width, height, centerline
def L(z):
 p,g=z[0],map(L,z[1:])
 if p=='*':
  if z[1][0]in'+-':g[0]=S(g[0])
  if z[2][0]in'+-':g[1]=S(g[1])
 if p=='^'and z[1][0]in'+-*/^!':g[0]=S(g[0])
 if g:(A,a,b,c)=g[0]
 if g[1:]:(D,d,e,f)=g[1]
 if p in'-+*=,':
  C=max(c,f);E=max(b-c,e-f);F=C+E;U=[s+s+s]*F;U[C]=s+p+s;V=3
  if p in'*,':U=[s]*F;V=1
  return([x+u+y for x,u,y in zip((C-c)*[s*a]+A+(E-b+c)*[s*a],U,(C-f)*[s*d]+D+(E-e+f)*[s*d])],a+d+V,F,C)
 if'^'==p:return([s*a+x for x in D]+[x+s*d for x in A],a+d,b+e,c+e)
 if'/'==p:w=max(a,d);return([(w-a+1)/2*s+x+(w-a)/2*s for x in A]+['-'*w]+[(w-d+1)/2*s+x+(w-d)/2*s for x in D],w,b+e+1,b)
 if'!'==p:return([' -  '[i==c::2]+A[i]for i in R(b)],a+2,b,c)
 if'I'==p:h=max(3,b);A=(h-b)/2*[s*a]+A+(h-b+1)/2*[s*a];return(['  \\/|/\\  '[(i>0)+(i==h-1)::3]+A[i]for i in R(h)],a+3,h,h/2)
 return([p],len(p),1,0)

print'\n'.join(L(P(T[1:-1]))[0])

For the big input in the question, I get:
 /\         2                     2
 |     - m x  b          2 + b m x
 |     --------    = - -------------
 |  3      2                    2
\/ x  e         dx         b m x
                           ------
                        2     2    2
                       b  e       m

Here's some more tricky test cases:
I:(2^3)^4
O:    4
  / 3\
  \2 /

I:(2(3+4)5)^6
O:             6
  (2 (3 + 4) 5)

I:x Integral[x^2,dx] y
O:   /\ 2
  x  | x  dx y
    \/

I:(-x)^y
O:     y
  (- x)

I:-x^y
O:     y
  (- x)

That last one is wrong, some precedence error in the parser.

shouldn't the baseline of the integral argument be verically centered after the integral? Currently it looks more like a subscript to the integral.

Not hard to change, but it would waste some space.  I currently make the integral sign just big enough to span its argument (with a 3 high minimum).

Slight golf: Use tabs instead of double spaces.


text:
Code-Challenge:The Nearest Prime
Challenge

In this task you would be given an
  integer N you have to output the
  nearest prime to the integer.

If the number is prime itself output the number.
The input N is given in a single line,the inputs are terminated by EOF.The number of inputs would not exceed 10000 values.
The challenge is to implement the fastest solution so that it can process a maximum of 10000 values as fast as possible.
Input
 299246598
 211571591
 71266182
 645367642
 924278231

Output
 299246587
 211571573
 71266183
 645367673
 924278233

Constraints

N is less than 2^64
Take care of your fingers do not use more than 4096 bytes in your solution.
You can use any language of your choice as long as you are not using it's any inbuilt things for the primes.
Fastest solution,with the most efficient time complexity wins!

ADDED:
This is a easier version of the this same problem (with N < 2^31) so that you may try checking your approach in smaller cases before building it up for this actual problem.

The basic calculation you're requestion was a sub-part of http://codegolf.stackexchange.com/q/1977/78, just a couple of days ago. Personally (i.e. not wearing my moderator hat) I find such repetition boring.

Can we use probabilistic primality tests?

How do you plan on judging fastest? By speed of execution on fixed hardware? Or by analyzing the complexity of the submissions? Will you somehow normalize the cost of operations in different languages? -- Lastly, this challenge seems way too simple. There really isn't any room to innovate here.

@dmckee:No that problem is way more simple and very weak itself.

Can I use a 2^64 lookup table?

@Keith Randall:My solution is developed on Miller-Rabin + an optimized sieve for small numbers but you may use fast deterministic tests too :-)

@MtnViewMark:I have mentioned in the constraints that the Fastest solution,with the most efficient time complexity wins! and I think it is not that simple,please take a look on the restrictions (carefully) and if you still find it way more simple and there isn't any room for innovation,then I am sorry,probably this challenge is not for you :-)

@gnibbler: Using a lookup table of all 2^64 values will give you the fastest solution iff you can squeeze the entire thing (solution) through the 4096 bytes window :-)

@Debanjan, may we assume the generalised Riemann hypothesis in stating time complexity?

@Peter Taylor: Okay :-)

Would you provide some more test data please?

Python
import sys,random

# Miller-Rabin primality test, error rate 2^-200.
def prime(N):
  if N<3:return N==2
  s=0
  d=N-1
  while (d&1)==0:s+=1;d>>=1
  for i in xrange(100):
    a=random.randrange(1,N)
    if pow(a,d,N)!=1 and all(pow(a,d<<r,N)!=N-1 for r in xrange(s)):return 0
  return 1

for N in map(int,sys.stdin):
  d=0
  while 1:
    if prime(N+d):print N+d;break
    if prime(N-d):print N-d;break
    d+=1

I think it should be noted that the Miller-Rabin primality test is not unconditionally deterministic. http://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test

PARI GP
a(n)=x=[precprime(n),nextprime(n)];print(if(x[1]-n<n-x[2],x[1],x[2]))
while(1,print(a(input())))

I suppose mathematica would be something similar but it's NextPrime[n] works strictly above n so 3 conditions....

Haskell
import Data.Numbers.Primes

-- Assuming, we are on x64
nearestPrime :: Int -> Int
nearestPrime n | n - s < l - n = s
               | otherwise     = l where
  l = head $ dropWhile (not . isPrime) [n..]
  s = head $ dropWhile (not . isPrime) [n,n-1..]

main = readLine >>= print . nearestPrime . read

Should be quite fast. Requires the package primes, available from hackage.

Sorry,that is not allowed,this is code challenge and I guess this should not work in the shorter version of the problem too.

As you said, importing code is a shame. Unless you judge others by another standard than your own

@belisarius You err. This is not code golf so code size is not an option. The task you attempted to solve was code golf however.

Using inbuilt primes is not a good choice as this is not codegolf and the whole point is to implement a fast approach This answer deserves a -1, clearly. I don't feel in a downvoting mood, though.

@belisarius If you have the need for any sort of "revenge", just vote me down. There is no problem with that; neverthless, that is bad style.

Ruby
require 'prime'
gets(p).split.each{|n|
    a=b=n.to_i
    a,b = a-1,b+1 while !a.prime?  and !b.prime?
    p a.prime? ? a : b
}

Using inbuilt primes is not a good choice as this is not codegolf and the whole point is to implement a fast approach,the decision of the best score is to be based on the complexity of the solution so this is not allowed,sorry.

Java
This takes <1 second until num starts being greater than 10^8. Not efficient enough, considering 2^64 is about 1.8*10^19. (Started 10^15 6 minutes ago, and is still running D:)
import java.util.*;

class ClosestPrime {

    public static double closest(double num) {
        double returnme = 0;
        if (isPrime(num)){returnme = num;}
        for (double i = 0; i < num / 2; i++) { //checks each side of num
            if (isPrime(num - i)) {returnme = num - i;
                break;}
            if (isPrime(num + i)) {returnme = num + i;
                break;}
        }
        return returnme;
    }

    private static boolean isPrime(double num) {
        long sqrtnum = (long) Math.sqrt(num); //no need to check for factors above sqrt(num)
        List<Double> primes = new LinkedList<Double>();
        primes.add((double) 2);
        for (double i = 3; i < sqrtnum; i+=2) {primes.add(i);} //fill list with odd numbers

        for (long i = 2; i <= sqrtnum; i++) {
            if (num / i % 1 == 0) {return false;}
            ListIterator<Double> iter = primes.listIterator();
            while (iter.hasNext()) {if ((iter.next()) / i % 1 == 0){iter.remove();}} //sieving by Eratosthenes
        }
        return true;
    }
}

This gives a surefire answer every time, since it doesn't use a probabilistic algorithm, but pays heavily for that in terms of efficiency - 10^18 would have over 5 million primes in the list, and even more before sieving. May improve this sometime with a better sieve algorithm. I don't expect this to beat any of the others :)

Haskell
This is pretty fast, and non-deterministic up to a large limit. Also my first ever Haskell :). wc says 903b uncompiled.
Edit: If anyone wants to estimate the time complexity, be my guest...
import System.Environment
import Math.NumberTheory.Moduli -- arithmoi
import Data.List.Ordered -- data-ordlist

main :: IO ()
main = interact processInputStrings

processInputStrings :: String -> String
processInputStrings input = unlines $ map show $ getClosestMembers $ map read $ lines $ input

isPrime :: Integer -> Bool
{- Implement the Miller–Rabin test with basis valid up to somewhere > 2^64 -}
isPrime 2 = True
isPrime 3 = True
isPrime t =  let
        factor :: (Integer, Integer) -> (Integer, Integer)
        factor (d,s) = if even d then factor (d `div` 2, s+1) else (d,s)
        (d,s) = factor (t-1, 0)
    in
        and $ map (\a ->
            or [(powerMod a d t) == 1, or [(powerMod a (2^r * d) t) == t-1 | r <- [0..s-1]]]
        ) $ filter (<t) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

getClosestMembers :: [Integer] -> [Integer]
getClosestMembers inputs = map (\i -> head [n | n <- concat [[i-d, i+d] | d <- [0..]], isPrime n]) inputs


text:
Long multiply, 8 bits at a time
You are given a 16-bit machine and told to implement multiplication of arbitrary-sized integers.  Your registers can only hold 16-bit numbers, and the biggest multiply instruction takes two 8-bit inputs and generates a 16-bit result.
Your program must take as input two arbitrary-sized positive numbers and output their product.  Each input number is encoded on its own line as a little-endian byte array where each byte is a 2-digit hex number.  The output must be similarly formatted.  Perhaps best explained with an example:
input
1f 4a 07
63 a3

output
fd 66 03 a7 04

which encodes the multiplication 477727*41827=19981887229.
You can assume that the last (most significant) byte of each input number is nonzero, and the last chunk of the number you output must be nonzero.  Both input numbers will be at most 100 bytes long.
Smallest code wins.
Remember, the biggest multiply you are allowed to use is 1 byte * 1 byte, and no integer types bigger than 2 bytes!

This is crucial for languages, that have no default 8-bit type, like Haskell.

What about addition? Can we pretend to have a ready-made arbitrary-size addition function? If not, what can we add?

@Timwi: You can do anything you'd like 16 bits at a time.  Adds, shifts, whatever.  Any larger operation you need to synthesize yourself.

+1 for correct byte order

Perl, 137 characters
($x,$y)=<>;while($x=~s/.. *//s){$e=hex$&;$i=0;$s=$r[$i]+=$e*hex,$r[$i]&=255,$r[++$i]+=$s>>8 for$y=~/.. */gs;$y="00$y"}printf'%02x 'x@r,@r

Caveats

Sometimes prints an extra 00 byte at the end of the result. Of course the result is still correct even with that extra byte.
Prints an extra space after the last hex byte in the result.

Explanation
The explanation is going to be a bit long, but I think most people here will find it interesting.
First of all, when I was 10 years old, I was taught the following little trick. You can multiply any two positive numbers with this. I will describe this using the example of 13 × 47. You start by writing the first number, 13, and dividing it by 2 (round down each time) until you reach 1:
13
 6
 3
 1

Now, next to the 13 you write the other number, 47, and keep multiplying it by 2 the same number of times:
13     47
 6     94
 3    188
 1    376

Now you cross out all the lines where the number on the left is even. In this case, this is only the 6. (I can’t do strike-through in code, so I’ll just remove it.) Finally, you add all the remaining numbers on the right:
13     47
 3    188
 1    376
     ----
      611

And this is the right answer. 13 × 47 = 611.
Now, since you are all computer geeks, you will have realised that what we’re actually doing in the left and right columns is x >> 1 and y << 1, respectively. Furthermore, we add the y only if x & 1 == 1. This translates directly into an algorithm, which I’ll write here in pseudocode:
input x, y
result = 0
while x > 0:
    if x & 1 == 1:
        result = result + y
    x = x >> 1
    y = y << 1
print result

We can re-write the if to use a multiplication, and then we can easily change this so that it works on a byte-by-byte basis instead of bit-by-bit:
input x, y
result = 0
while x > 0:
    result = result + (y * (x & 255))
    x = x >> 8
    y = y << 8
print result

This still contains a multiplication with y, which is arbitrary-size, so we need to change that into a loop too. We’ll do that in Perl.
Now translate everything to Perl:

$x and $y are the inputs in hex format, so they have the least significant byte first.
Thus, instead of x >> 8 I do $x =~ s/.. *//s. I need the space+star because the last byte might not have a space on it (could use space+? too). This automatically puts the removed byte (x & 255) into $&.
y << 8 is simply $y = "00$y".
The result is actually a numerical array, @r. At the end, each element of @r contains one byte of the answer, but halfway through the calculation it may contain more than one byte. I’ll prove to you below that each value is never more than two bytes (16 bits) and that the result is always one byte at the end.

So here is the Perl code unravelled and commented:
# Input x and y
($x, $y) = <>;

# Do the equivalent of $& = x & 255, x = x >> 8
while ($x =~ s/.. *//s)
{
    # Let e = x & 255
    $e = hex $&;

    # For every byte in y... (notice this sets $_ to each byte)
    $i = 0;
    for ($y =~ /.. */gs)
    {
        # Do the multiplication of two single-byte values.
        $s = $r[$i] += $e*hex,
        # Truncate the value in $r[$i] to one byte. The rest of it is still in $s
        $r[$i] &= 255,
        # Move to the next array item and add the carry there.
        $r[++$i] += $s >> 8
    }

    # Do the equivalent of y = y << 8
    $y = "00$y"
}

# Output the result in hex format.
printf '%02x ' x @r, @r

Now for the proof that this always outputs bytes, and that the calculation never generates values greater than two bytes. I’ll prove this by induction over the while loop:

The empty @r at the beginning clearly has no values greater than 0xFF in it (because it has no values in it at all). This concludes the base case.
Now, given that @r contains only single bytes at the beginning of each while iteration:

The for loop explicitly &=s all values in the result array with 255 except the last one, so we only need to look at that last one.
We know that we always remove only one byte from $x and $y:

Therefore, $e*hex is a multiplication of two single-byte values, which means it’s in the range 0 — 0xFE01.
By the inductive hypothesis, $r[$i] is one byte; therefore, $s = $r[$i] += $e*hex is in the range 0 — 0xFF00.
Therefore, $s >> 8 is always one byte.

$y grows an extra 00 in each iteration of the while loop:

Therefore, in every iteration of the while loop, the inner for loop runs for one more iteration than it did in the previous while iteration.
Therefore, the $r[++$i] += $s >> 8 in the last iteration of the for loop always adds $s >> 8 to 0, and we already established that $s >> 8 is always one byte.

Therefore, the last value stored in @r at the end of the for loop is also a single byte.

This concludes a wonderful and exciting challenge. Thanks a lot for posting it!

C Solution
This solution does no input validation.  It's also only lightly tested.  Speed was not really a consideration.  Malloc's memory, and isn't particularly clever about how much it grabs.  Guaranteed to be enough, and more than necessary.
m() accepts a string, expects two newlines in the string, one after each number.  Expects only numbers, lowercase characters, spaces, and newlines.  Expects hex digits to always be a pair.
No multiply operation is ever used (knowingly).  Shifting is performed on 8-bit variables.  One 16-bit addition is performed.  No 32-bit data types.
Shrunk by hand, and only mildly.  edit: more obfuscation, fewer chars :D  Compiles with warnings with gcc.
Characters: 675
typedef unsigned char u8;
#define x calloc
#define f for
#define l p++
#define E *p>57?*p-87:*p-48
#define g(a) --i;--a;continue
void m(u8*d){short n=0,m=0,a,b,i,k,s;u8*t,*q,*r,*p=d,o;f(;*p!=10;n++,l){}l;f(;*p
!=10;m++,l){}t=x(n,1);q=x(m,1);r=x(n,1);p=d;a=n;i=0;f(;*p!=10;i++,l){if(*p==32){
g(a);}t[i]=E;t[i]<<=4;l;t[i]|=E;}a/=2;b=m;i=0;l;f(;*p!=10;i++,l){if(*p==32){g(b)
;}q[i]=E;q[i]<<=4;l;q[i]|=E;}b/=2;f(k=0;k<8*b;k++){if(q[0]&1){o=0;f(i=0;i<n;i++)
{s=o+t[i]+r[i];o=s>>8;r[i]=s&255;}}f(i=n;i;i--){o=t[i-1]>>7&1;t[i-1]*=2;if(i!=n)
t[i]|=o;}f(i=0;i<m;i++){o=q[i]&1;q[i]/=2;if(i)q[i-1]|=(o<<7);}}k=(r[a+b-1]==0)?a
+b-1:b+a;f(i=0;i<k;i++){printf("%02x ",r[i]);}putchar(10);}

You can test with this:
int main(void){
  m("1f 4a 07\n63 a3\n");
  m("ff ff ff ff\nff ff ff ff\n");
  m("10 20 30 40\n50 60 70\n");
  m("01 02 03 04 05 06\n01 01 01\n");
  m("00 00 00 00 00 00 00 00 00 00 00 00 01\n00 00 00 00 00 00 00 00 02\n");
  return 0;
}

Result:
$ ./long
fd 66 03 a7 04
01 00 00 00 fe ff ff ff
00 05 10 22 34 2d 1c
01 03 06 09 0c 0f 0b 06
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02

OCaml + Batteries, 362 characters
A standard O(n*m) schoolboy multiplication algorithm. Note that in order to meet the challenge requirements, the operations are done on the bytes of strings, which in OCaml are (conveniently, in this case) mutable. Note also that the accumulator s never overflows 16 bits, since 2(2^8 - 1) + (2^8 - 1)^2 = (2^8 - 1)(2^8 + 1) = 2^16 - 1.
let(@)=List.map
let m a b=Char.(String.(let e s=of_list(((^)"0x"|-to_int|-chr)@nsplit s" ")in
let a,b=e a,e b in let m,n=length a,length b in let c=make(m+n)'\000'in
iteri(fun i d->let s,x=ref 0,code d in iteri(fun j e->let y=code e in
s:=!s+code c.[i+j]+x*y;c.[i+j]<-chr(!s mod
256);s:=!s/256)b;c.[i+n]<-chr!s)a;join" "((code|-Printf.sprintf"%02x")@to_list c)))

For example,
# m "1f 4a 07" "63 a3" ;;
- : string = "fd 66 03 a7 04"

# m "ff ff ff ff" "ff ff ff ff" ;;
- : string = "01 00 00 00 fe ff ff ff"

JavaScript (Node.js), 160 bytes
x=>y=>x.map((t,i)=>y.map(u=>(f=i=>(c=s[i]>>8)&&f(i++,s[i]=c+~~s[i],s[i-1]%=256))(i,s[i]=~~s[i++]+`0x${t}`*`0x${u}`)),s=[])&&s.map(t=>(t<16?0:'')+t.toString(16))

Try it online!
Lot newer language than that time though

8086 DOS .COM file, 134 bytes
It works now!
What better language to do this in than 16-bit assembly?
00000000: b9 c8 00 89 cd 31 c0 f3 50 89 e7 e8 5d 00 92 aa  .....1..P...]...
00000010: 74 f9 29 e7 87 fb 89 e6 8d 3a e8 4e 00 9c 56 57  t.)......:.N..VW
00000020: 89 d9 ac f6 e2 03 05 ab 83 15 00 4f e2 f4 5f 5e  ...........O.._^
00000030: 47 9d 74 e6 80 39 00 74 01 4b 01 df 01 e5 29 ef  G.t..9.t.K....).
00000040: 89 ee ac 88 c3 b1 04 d2 e8 e8 10 00 93 24 0f e8  .............$..
00000050: 0a 00 b0 20 e8 0d 00 4f 75 e8 cd 20 3c 09 76 02  ... ...Ou.. <.v.
00000060: 04 27 04 30 b4 02 88 c2 cd 21 c3 b2 00 b4 01 cd  .'.0.....!......
00000070: 21 2c 30 72 0e 3c 0a 72 02 2c 27 b1 04 d2 e2 00  !,0r.<.r.,'.....
00000080: c2 eb ea 3c f0 c3                                ...<..

My first, and likely last 16-bit 8086 program.
Assembly (NASM with C comments because of syntax highlighting):
        // sed -i -e 's#//#;#g' dosmult.asm
        // nasm -f bin dosmult.asm -o dosmult.com

        // The default, but never harmed anyone.
        [bits 16]
        // 8086 code only! If I use 386 instructions or any of that,
        // I would ruin the challenge.
        [cpu 8086]
        // COM files start at 100h.
        org 100h

        section .text

start:
        // Create a 400 byte buffer on the stack.
        // 200 will be reserved for the input, and 200 for the output.
        mov     cx, 200
        // Save 200 in BP for later, it will be useful.
        mov     bp, cx
        // Push 0 200 times making a 400 byte zeroed buffer on the stack
        xor     ax, ax
        rep     push ax

        mov     di, sp
        // Read the first line of hex digits.
.getline_loop:
        call    gethex
        // Swap DL to AL and store with STOSB
        xchg    dx, ax
        stosb
        // Loop if it was a space
        jz      .getline_loop

        // Get length
        sub     di, sp
        // Store length in BX
        xchg    di, bx
        // Save the pointer to input in SI
        mov     si, sp
        // Load the pointer to output in DI (SI + 200)
        lea     di, [si + bp]

        // Begin multiplication, grade school byte by byte
        // Instead of creating a third buffer, we process the data
        // as the user inputs it.
.loop:
        call    gethex
        // Save flags from gethex so we know when to stop
        pushfw
        // Save SI and DI
        push    si
        push    di
        // Loop counter
        mov     cx, bx
.mult_loop:
        // Load next byte from first input
        lodsb
        // Multiply by the input byte
        mul     dl
        // 16-bit add to [DI]
        // We actually add to AX, then do STOSW.
        add     ax, [di]
        stosw
        // Add the carry bit.
        adc     word [di], 0
        // Decrement DI after STOSW incremented it by 2 to iterate
        // on each byte.
        dec     di
        // while (--cx)
        loop    .mult_loop
.mult_loop_end:
        // Restore DI and SI
        pop     di
        pop     si
        // Increment output pointer
        inc     di
        // Restore flags from gethex
        popfw
        // Jump if we got a space.
        jz      .loop

.loop_end:
        // Was there a trailing zero?
        cmp     byte[di + bx], 0
        jz      .nodec
.dec:
        // If so, decrement the count.
        dec     bx
.nodec:
        // Calculate the length with ugly pointer arithmetic.
        // I feel there is a better way to do this.
        add     di, bx // ptr += len
        add     sp, bp // sp += 200 (sp = output)
        sub     di, sp // ptr -= output
        // Store output array in SI.
        mov     si, sp
        // Print each byte in hex
.print_loop:
        // Load byte
        lodsb
        // puthex(AL >> 4)
        mov     bl, al
        mov     cl, 4
        shr     al, cl
        call    puthex
        // puthex(AL & 0Fh)
        xchg    ax, bx
        and     al, 0Fh
        call    puthex
        // putc(' ')
        mov     al, ' '
        call    putc
        // Loop for every byte from DI.
        dec     di
        jnz     .print_loop
.print_loop_end:
        // exit, not bothering to clean anything up. :P
        int     20h

        // Prints hex digit in AL.
        // Must be <= 0fh
puthex:
        cmp     al, 9
        jbe     .no_hexa
.hexa:
        add     al, 'a' - '9' - 1
.no_hexa:
        add     al, '0'
        // Fallthrough

        // Prints AL to stdout.
putc:
        mov     ah, 2h
        mov     dl, al
        int     21h
        ret

        // Reads a hex byte.
        // Returns in DL.
        // Sets whether it ended in a space in the Z flag.
gethex:
        mov     dl, 0
.start:
        // Read char into AL
        mov     ah, 1h
        int     21h
        // Subtract ASCII '0'
        sub     al, '0'
        // If we hit a space or newline, they will trigger the 'below'
        // condition
        jb      .ret
        // Was AL '0'-'9'? If not, correct it to 'a'-'f'.
        cmp     al, 10
        jb      .no_hexa
.hexa:
        // Correct AL
        sub     al, 'a' - '9' - 1
.no_hexa:
        // DL = (DL << 4) + AL
        // 8086 doesn't have shift by immediate.
        mov     cl, 4
        shl     dl, cl
        // Add to BL
        add     dl, al
        // Loop
        jmp     .start
.ret:
        // Check if AL before the subtraction was a space.
        cmp     al, ' ' - '0'
        ret

Naturally, being a 16-bit instruction set, I am only doing 8-bit and 16-bit arithmetic (and I don't use the 16-bit mul).
Beats the Perl answer by 3 bytes. Granted, this is binary machine code and that is source code, so I guess this isn't that much to get excited about. However, 8086 lacks a lot of the features Perl has (about 1/3 of it is just I/O and hex conversion ).
I am sure there are multiple optimizations possible here. A lot of my knowledge is from writing 32-bit and 64-bit code, so I am not fully knowledgeable in the 16-bit tricks.
Input is from stdin, in space separated lowercase hex, each ending in a new line. It is not line buffered, so no typos allowed! :P
Output is printed to stdout.