text:
Print the prime factorization of the greatest common divisor of two numbers
Title says it all. Two input 32-bit positive integers m, n >= 2, output gcd(m,n) in prime factorization form.
Input
Command line args or 1 line of stdin okay, whatever's better for golf.
Output
Single space delimited with exponents (no additional spaces). Output nothing if the inputs are relatively prime.
Examples:
$ ./factorize 96 162
2^1 3^1

$ ./factorize 14 15

$ ./factorize 196 294
2^1 7^2

Rules

You may not use external resources, math libraries or built-in functions for factorization or GCD. Examples: Java, no java.lang.Math. ruby, no prime_division, perl, no factor, etc.

What output are you looking for if gcd(n,m) == 1?

Is it okay if I exit with an exception? It would save me a few bytes.

Actually, I've changed my approach and have no need to exit with an exception. Others might want to know, though.

Do not exit with an exception. Output nothing :)

Technically, q:a+.b or __ q:a+.b in J uses no external resources or math libraries, but I won't post it, since it's too far from the spirit of the question. I just thought I'd share it here.

Python 3, 255 250  237 226 188 180 150 142 137 136 chars
a,b=map(int,input().split())
t,g='',1
while g<a:
 g,p=g+1,0
 if a%g+b%g<1:
  while a%g+b%g<1:a/=g;b/=g;p+=1
  t+='%d^%d '%(g,p)
print(t)

It's amazing how much I could shorten this by just skipping stuff (like, you know, finding the gcd)! Also I could reduce 10 more chars by making this a function that expects 2 ints, like some other answers, instead of reading from stdin.

This is intense! I'm learning a lot by watching your edits and trying to beat you lol. I think you might have this one though (out of the Python answers)

You can save 1 character by changing while g<a and g<b: to while(g<a)*(g<b):

@Rusher Thanks mate! Your answer is the one that motivated me to work harder on this :) Also the trick you recommended inspired me to figure out the a%g+b%g bit

I don't think the else clause is necessary. else:g+=1 could just be g+=1, unless I'm missing something.

@isaacg You seem to be right, thank you!

You can save another 3 characters indenting with space and Tab instead of space and double space.

@avall That doesn't work in Python 3... I really need to install 2.x again just for these golf stuff :)

@Tal Move the p=0 outside of the if clause, up two lines, to save a character.

@Tal change g<a to g<=a as you don't cover case of a==b, check my answer

@mleko It seems like you're correct, but it still works for a==b, including when they're prime. I'm not sure how, actually.

@Tal hmm, I get wrong results $ python3 golf.t.py  12 12 2^2

@mleko I noticed that I wasn't actually running the same code, because I'd been golfing it some more, so it actually is possible that that version wasn't working (now updated). This one, however, definitely outputs 2^2 3^1 for the input 12 12 when run on Python 3.2.

Ruby - 168 117 114 101 100 97
Edit: After thinking about it, realized I didn't need the sieve since the primality of the factor is taken care of in the factorization loop. Also, as informed by answers of others (laindir's and Tal's are the ones I had seen it in, though it looks like others have also done it), removed separate gcd calculation, since that also occurs in the factorization.
Edit 2: Don't need do.
Edit 3: Squeezing it down more.
Edit 4: Pulled out one more space.
Edit 5: upto instead of each; ?^ == "^"!
a,b=ARGV.map{|i|i.to_i}
2.upto(a){|d|c=0
[c+=1,a/=d,b/=d]while a%d+b%d<1
print d,?^,c," "if c>0}

Output (same after edit):
$ ruby factorize.rb 96 162
2^1 3^1
$ ruby factorize.rb 14 15

$ ruby factorize.rb 196 294
2^1 7^2

Certainly could be made better, but not bad for my first one.

You can remove 4 bytes by changing map{|i|i.to_i} to map &:to_i. You can remove a 5th byte by not counting the newline at end of file; Ruby works without it.

Also, you can use $* instead of ARGV.

Python 2 - 254 252 196 185 156 151 134 126 121
i=1
a,b=map(int,raw_input().split())
while b:a,b=b,a%b
while~-a:
 i+=1;j=0
 while a%i<1:j+=1;a/=i
 if j:print`i`+'^'+`j`,

Interpreter
repl.it
Example Input - stdin

100 50

Example Output - stdout

2^1 5^2

What about …`a`+'^'+`f.count(a)`…?

Pretty clean, I like it

@qwr Thanks. I hope I can understand the other Python answers String formatting and shave a few characters.

Swap f.append(i) for f+=[i] to save 5 characters.

@NolenRoyalty Thanks! Never knew you could do that.

And now you don't need to use f at all :p (why is f='' still there?)

@NolenRoyalty Hahaha... oops. Good catch.

Java - 184 175
This is inspired by @Geobits (and a little of @Tal's answer) answer, but enough of it is different that I decided to create my own answer.
class G{public static void main(String[]a){for(Integer i=1,q,n=i.valueOf(a[0]),m=i.valueOf(a[1]);m>=++i;System.out.print(q>0?i+"^"+q+" ":""))for(q=0;n%i+m%i<1;n/=i,m/=i)q++;}}

Ungolfed (sort of) with (human verification) test harness:
class G {
    public static void mainMethod(String[] a) {
        for (Integer i = 1, q, n = i.valueOf(a[0]), m = i.valueOf(a[1]); m >= ++i;
                 System.out.print(q > 0 ? i + "^" + q + " " : ""))
            for (q = 0; n % i + m % i < 1; n /= i, m /= i)
                q++;
    }

    public static void main(String[] a) {
        m(3, 3);
        m(196, 294);
        m(294, 196);
        m(14, 15);
        m(15, 14);
        m(96, 162);
        m(162, 96);
        m(300, 400);
        m(400, 300);
        m(100, 100);
        m(7, 7);
        m(4, 8);
    }

    public static void m(int one, int two) {
        mainMethod(new String[] { String.valueOf(one), String.valueOf(two) });
        System.out.println();
    }
}

dc, 96 bytes
?sbsa2sf[q]sk[lalf~lblf~szrlz+0<ksbsale1+selsx]ss[lfn[^]Plen[ ]P]sp[0selsxle0<plf1+dsflb!<w]dswx

It reads one line of standard input. Its output does not end with a newline. (EDIT: It does also output an extra space after every factorization. Some of the other answers trim the space, but this one doesn't.)
Example:
$ echo 301343045 421880263 | dc factorize.dc
1021^1 59029^1 $

Code with comments:
# dc(1) is a stack language, like Forth. Programs push values on the
# stack, then operate on them. For example, to calculate
#  (2 + 3) * (9 - 4)
# the dc code is
#  [2 3 + 9 4 - *]

# [?] reads a line of input.  We expect two integers >= 2.
# [sb sa] stores the integers in variables.
? sb sa     # a, b = two integers from input

# This program sucks common factors from a and b, looping for
# f = 2, 3, 4, 5, and so on.  This method only sucks prime factors,
# but wastes time when f is not prime.
2 sf        # f = 2

# Code in [...] does not run until the program calls it.

# k = code to break a loop
[
 q           # [q] breaks two levels of [...]
] sk        # k = break

# s = loop to suck factor f from a and b
#  This loop increments e, the exponent for factor f.
#  Please set e = 0 before entering this loop.
[
 # [la lf] puts ( a f ) on the stack.
 # [~] does division and remainder.
             # STACK:
 la lf ~     # ( a/f a%f )
 lb lf ~     # ( a/f a%f b/f b%f )

 # [r] swaps the top two stack values.
 # Hold z = b%f and swap a%f with b/f.
             # STACK:
 sz r lz     # ( a/f b/f a%f b%f )

 # f is a common factor if a%f and b%f are zero.  Because a and b are
 # non-negative, a%f and b%f are zero only if a%f+b%f is zero.
             # STACK:
 +           # ( a/f b/f a%f+b%f )

 # Call k to break loop unless a%f+b%f is zero.  [<k] conditionally
 # calls k if the comparison is true.  Comparisons in dc are
 # backwards, so [3 0 <k] would check 0 < 3.  Because a%f+b%f is never
 # negative, [0 <k] is golf for [0 !=k].
             # STACK:
 0 <k        # ( a/f b/f )

 # f is a common factor, so suck it!
 sb sa       # a = a/f, b = b/f, STACK: ( )
 le 1 + se   # increment e, the exponent for this factor
 ls x        # continue loop, [x] executes s
] ss        # s = loop

# p = code to print "f^e "
[
 # [n] prints a number without a newline.
 # [P] prints a string.
 lf n [^]P
 le n [ ]P

 # DEBUG: Uncomment to print a and b.
 #[(a = ]P la n [, b = ]P lb n [)]P 10P
] sp        # p = print

# w = loop to iterate factors
[
 # Call s loop to suck factor f from a and b, and set exponent e.
 0 se        # e = 0
 ls x        # call s loop

 # DEBUG: Uncomment [c] to clear the stack.  Loop s leaves two junk
 # values ( a/f b/f ) on the stack.  Deleting [c] for code golf saves
 # 1 byte but leaks junk on the stack.
 #c

 # Print "f^e " if 0 < e.  Comparisons in dc are backwards, so
 # [0 le <p] would check e < 0, [le 0 <p] checks 0 < e.
 le 0 <p

 # Increment f.  [d] duplicates top value on stack.
             # STACK:
 lf 1 +      # ( f+1 )
 d           # ( f+1 f+1 )
 sf          # ( f ) as f+1 becomes f

 # Continue loop if b >= f.  This is golf for f <= a and f <= b, as
 # extra iterations of the loop cause no harm.
             # STACK:
 lb          # ( f b )
 !<w         # ( ), continue loop if not b < f
] d sw      # w = loop; STACK: ( w )
x           # enter loop unconditionally; STACK: ( ) at entrance

JavaScript (ECMAScript 6 Draft) - 89 Characters
f=(m,n,i=2,k=0)=>(m%i|n%i?(k?i+'^'+k+' ':'')+(i>m?'':f(m,n,i+1)):f(m/i,n/i,i,k+1)).trim()

Converts the original (iterative) answer, below, into a recursive one.
Explanation
f=(m,n,i=2,k=0)=>           // A function with arguments m and n and optional arguments
                            // i (defaults to 2) and k (defaults to 0)
  (
    m%i|n%i                 // if i is not a divisor of m or n then:
      ?(k?i+'^'+k+' '       //   if k is non-zero append  "i^k " to the output
         :'')               //   else append nothing
        +(i>m?''            //   if i>m then terminate
             :f(m,n,i+1))   //   else increment i and reset k to 0
      :f(m/i,n/i,i,k+1)     // else divide m and n by i and increment k
  ).trim()                  // finally strip any extra spaces from the output.

Iterative Answer: JavaScript (ECMASCript 6) - 108 (or 121) 98 Characters
Version 2:
f=(m,n)=>{for(s='',i=1;++i<=m;s+=k?' '+i+'^'+k:'')for(k=0;m%i+n%i<1;k++)m/=i,n/=i;return s.trim()}

Version 1:
Answering the question as originally asked:
f=(m,n)=>{for(o=[],i=2;i<=m;)m%i|n%i?i++:(m/=i,n/=i,o[i]=(o[i]|0)+1);return o.map((x,i)=>i+"^"+x).join(' ')}

Or to comply with the rule changes after the fact:
f=(m,n)=>{for(o=[],i=2;i<=m;)m%i|n%i?i++:(m/=i,n/=i,o[i]=(o[i]|0)+1);return o.map((x,i)=>i+"^"+x).filter(x=>x).join(' ')}

Explanation
f=(m,n)=>                        // Create a function f with arguments m and n
{
  o=[]                           // Initialise an empty array for the output
  i=2                            // Start with a divisor of 2
  for(;i<=m;)                    // Loop while the divisor is not greater than m
    m%i|n%i                      // Test the bitwise OR of m%i and n%1 (i.e. whether
                                 // at least one is non-zero)
      ?i++                       // If m%i>0 or n%i>0 then increment i
      :(m/=i,                    // Otherwise: divide m by i;
        n/=i,                    //                   n by i;
        o[i]=(o[i]|0)+1);        // and add 1 to the i-th element of o
  return o.map((x,i)=>i+"^"+x)   // finally map the sparse array o to a sparse array
                                 // of the strings (index+"^"+value)
          .filter(x=>x)          // turn sparse array into non-sparse array
          .join(' ')             // then concatenate and return.
}

Output
f(96,162)
"2^1 3^1"

f(14,15)
""

f(80, 80)
"2^4 5^1"

f(196,294)
"2^1 7^2"

Hey can you try testing f(158,237) please

It is space delimited with exponents (it just happens to have a lot of space) "                                                                               79^1"

Right, the other solutions don't have that and neither does the example. Please fix :)

Nothing in the question, as originally asked, defines how much whitespace is or is not allowed - as I see it, this meets the requirements as it is whitespace delimited with exponents. However, you're going to go and change the rules now aren't you?

Under the preexisting rules, one could say that this implementation omits the requirement "Output nothing if the inputs are relatively prime." Still seems wrong to deface golf code that came out so pretty. How brief can you make a filter() call?

.filter(x=>x) - 13 characters

That function syntax is so enviable. One day it will be mine.

This recursive function failed on f(301343045, 421880263); probably because my browser will not let me recurse that deep. Stupid broken Firefox!

Yes, SpiderMonkey throws a RangeError: Maximum call stack size exceeded when I try to do that as well - but the non-recursive ones work for larger numbers.

Perl 6: 90 characters, 94 bytes
sub MAIN(*@n){@n.any%$_||(my$p=$p⊎$_;@n»/=»$_;redo)for
2..@n[0];$p.pairs.fmt("%d^%d").say}

Somewhat de-golfed and commented:
sub MAIN (*@n) { # accept any number of input numbers as @n
    (
        # $p is a Bag, e.g., it holds the primes and the number of times each was added
        my $p = $p ⊎ $_; # Add the prime to the bag
        @n »/=» $_; # Divide all the input numbers by the prime

        redo # Redo the loop iteration with the same prime, in case
             # the numbers can be divided by it multiple times
    )
    if @n.all %% $_ # Do the above only if all of @n are divisible by $_
    for 2..@n[0];   # Do the above for all numbers from 2 .. @n[0]

    $p.pairs.fmt("%d^%d").say # Print join " ", "$prime^$count"
}

Usage is like:
$ perl6 -e'sub MAIN(*@n){@n.any%$_||(my$p=$p⊎$_;@n»/=»$_;redo)for
2..@n[0];$p.pairs.fmt("%d^%d").say}' 51 153
3^1 17^1

⊎ is a symbol in perl? I didn't know that.

@durron597 Only Perl 6 :)

PowerShell - 82
$a,$b=$args
2..$a|%{$p=0;while(!($a%$_+$b%$_)){$a/=$_;$b/=$_;$p++}if($p){"$_^$p"}}

This one is short and easy to read. It pipes the range 2..$a into a Foreach-Object loop %{...}. The loop collects the values of if($p){"$_^$p"}.

Perl, 144 133 118 114 97 93
($a,$b)=<>=~/\d+/g;for(2..$a){for($n=0;$a%$_+$b%$_<1;$n++,$a/=$_,$b/=$_){}$n&&print"$_^$n ";}

Ungolfed version:
($a,$b)=<>=~/\d+/g;
for(2..$a){
    for($n=0 ; $a%$_+$b%$_<1 ; $n++,$a/=$_,$b/=$_) {}
    $n&&print"$_^$n ";
}

I've literally just started learning Perl just to answer this question (this is my first Perl code ever), so I suspect that this can be golfed down further.

Yes, I haven't looked at your code closely, but foreach is always synonymous with for in Perl 5, so that should cut off 4 chars :)

@Mouq I've never seen a language with so much redundancy... thanks :)

Java : 247 241
Keeps track of factors in an array and just prints them out in a loop.
Decent size for Java, it seems.
class G{public static void main(String[]a){Integer i=1;int n=i.valueOf(a[0]),m=i.valueOf(a[1]),f[]=new int[n>m?n:m+1];for(;m>=++i||n>i;){if(n%i+m%i<1){f[i]++;n/=i;m/=i--;}}for(i=2;i<f.length;System.out.print(f[i]>0?i+"^"+f[i]+" ":""),i++);}}

// line breaks below

class G{
    public static void main(String[]a){
        Integer i=1;int n=i.valueOf(a[0]),m=i.valueOf(a[1]),f[]=new int[n>m?n:m+1];
        for(;m>=++i||n>i;){
            if(n%i+m%i<1){
                f[i]++;n/=i;m/=i--;
            }
        }
        for(i=1;i<f.length;System.out.print(f[i]>0?i+"^"+f[i]+" ":""),i++);
    }
}

You can actually leave the other variables as int, you lose 4 to the int  but you gain them back with new int[ -> new Integer[ so it's a wash.

Yeah, and I got another three by switching n%i<1&&m%i<1 to n%i+m%i<1.

You don't need the (). If n==m, it'll default to m+1 anyway.

You can replace m/=i;i=1; with m/=i--; It will run faster too :)

Are the braces after the first for loop necessary?

JavaScript (ECMAScript 5) 170 164 163 113
I pretty much couldn't resist following MT0's lead. I had considered recursion before, but it had seemed too easy to mess up. And it really is. The slightest variation wrecks everything.
There's a fiddle for those who like fiddles.
function f(a,b,i,e){return i?a%i|b%i?(e?i+'^'+e+' ':'')+(i>a?'':f(a,b,i+1,0)):f(a/i,b/i,i,e+1):f(a,b,2,0).trim()}

Ungolfed:
function f(a,b,i,e){
    return i // Check for factor.
        ?a%i|b%i // Check for indivisibility.
            ?(
                e // Check for exponent.
                    ?i+'^'+e+' ' // Add the current factor to result string.
                    :'' // Omit the current non-factor.
             )+(
                i>a // Check for termination state.
                    ?'' // Stop recursion.
                    :f(a,b,i+1,0) // Go to the next factor.
            )
            :f(a/i,b/i,i,e+1) // Failed indivisibility check. Increment exponent and divide subject values.
        :f(a,b,2,0) // Add default factor and exponent.
        .trim() // Get rid of one extra space that's usually on the end.
}

Old Version
function f(a,b){for(var r=[],j=-1,i=2;i<=a;)a%i|b%i?++i:(r[j]&&r[j][0]==i?r[j][1]++:r[++j]=[i,1],a/=i,b/=i);for(j=0;i=r[j];++j)r[j]=i.join('^');return r.join(' ')}

Ungolfed:
function f(a,b){
    for(var r=[],j=-1,i=2;i<=a;)
        // We (mis)use conditional expression `?:` instead of `if(){}else{}`.
        a%i|b%i ? // Bitwise OR saves one character over logical OR, where applicable.
             // In the truth case, `i` has become uninteresting. Just move on.
            ++i : // We don't mind hitting composites because their prime factors have already been drained from `a` and `b`.
            (
                r[j]&&r[j][0]==i ? // Check if `i` is already a listed factor.
                    r[j][1]++ : // Increment the exponent count.
                    r[++j]=[i,1], // Otherwise, add a new factor with exponent 1.

                a/=i,b/=i // Drain a used-up factor from `a` and `b`.
            );

    // The real work's done. Now we just format.
    for(j=0; i=r[j]; ++j)
        r[j]=i.join('^'); // Join each factor to its exponent.

    return r.join(' ') // Join all factors into result string.
}

Here are a few tests:
[
    f(4, 12),
    f(80, 80),
    f(96,162),
    f(196,294)
];

This recursive function failed on f(301343045, 421880263); probably because my browser will not let me recurse that deep. Stupid broken Firefox!

Certainly. In practice I'd only use a recursive function if I really needed some kind of stack, like for tree navigation or other inherently recursive data-structures. (Sure, numbers can be treated as recursive data-structures, but we have all kinds of nice abstractions to help us ignore that fact.)

GolfScript, 68 bytes
~..),2>*${1$1$%3$2$%+!{.@@/@2$/.}*;}/;;]:D.&{`.[~]D\/,(`"^"\++}%" "*

Note that this approach requires O(b2) time and space for integers “a” and “b”.
At the cost of one extra byte, "only" O(b) time and space are necessary:
~.),2>31*${1$1$%3$2$%+!{.@@/@2$/.}*;}/;;]:D.&{`.[~]D\/,(`"^"\++}%" "*

How it works
~.        # Interpret the input string (“a” and “b”) and duplicate “b”.
.),2>     # Push the array [ 2 3 4 ... b ].
*$        # Repeat each element b times and sort: [ 2 ... 2 3 ... 3 ... b ... b ]
{         # For each element “d” of the array:
  1$1$%   # Calculate a % d.
  3$2$%   # Calculate b % d.
  +!      # Add and negate.
  {       # If both “a” and “b” are divisible by “d”:
    .@@/  # Calculate a / d.
    @2$/  # Calculate b / d.
    .     # Create a dummy value.
  }*      #
  ;       # Pop the topmost stack element (non-divisor “d” or dummy value).
}/        #
;;]       # Pop “a” and “b” and collect the remaining stack elements in an array.
:|.&      # Save that array in “D” and intersect it with itself to deduplicate it.
{         # For each element “d” of “D”:
  `.[~]   # Push string "d" and array [d].
  D\/,(`  # Split “D” around [d] and take the length minus 1. This count the occurrences.
  "^"\    # Push the string "^" and swap it between "d" and it's number of occurrences.
  ++      # Concatenate the three strings.
}%        # Collect all strings into an array.
]" "*     # Join by spaces.

awk - 115 111 96 85
New version can only handle one line of input. Thanks to durron597 for pointing out that I only need to make sure i <= $1.
{for(i=1;++i<=$1;)for(;$1%i+$2%i==0;f[i]++){$1/=i;$2/=i}$0=z;for(i in f)$i=i"^"f[i]}1

Ungolfed:
{
    #skip finding gcd as a separate step, get it from the factors
    for(i = 1; ++i <= $1;) {
        for(;$1 % i == 0 && $2 % i == 0; f[i]++) {
            $1 /= i;
            $2 /= i;
        }
    }
    $0 = "";
    for(i in f) {
        $i = i "^" f[i];
    }
    print;
}

Previously could take pairs of numbers repeatedly
{a=$1;b=$2;for($0=c;a-b;)if(a>b)a-=b;else b-=a;for(i=2;i<=a;i++){for(j=0;a%i==0;j++)a/=i;$0=$0(j?i"^"j" ":c)}}1

Ungolfed:
{
    a = $1;
    b = $2;
    $0 = "";
    #rip off Euclid
    for(; a != b;) {
        if(a > b) {
            a = a - b;
        } else {
            b = b - a;
        }
    }
    #but not Eratosthenes
    for(i = 2; i <= a; i++) {
        for(j = 0; a % i == 0; j++) {
            a /= i;
        }
        $0 = $0 (j ? i "^" j " " : "");
    }
    print;
}

Do you need &&i<=b?

Well I'll be... you're right, you don't: if i > b, then b % i != 0 ...thanks :)

This program does not work with awk in OpenBSD 5.5, because NF=0; fails to delete $1 and $2. The output from echo 301343045 421880263 | awk -f factorize.awk | sed 's/  */ /g' is 5 7 1021^1 59029^1 because $1 is 5 and $2 is 7. The sed squeezes the extra spaces that come from printing $1022, $1023, $1024, ..., $59028 as empty strings joined by spaces.

Thanks @kernigh, it works in nawk, mawk, and gawk. Double-checked that posix says nothing about assigning to NF, and replaced with $0=z;

@laindir That change fixes the program for me. Code golf does not require programs to be portable. Luckily $0=z; is the same number of characters as NF=0;. If $0=z; was longer, I would tell you to keep NF=0;.

True, but it certainly makes it easier for people to verify it.

Python 3 (123)
This uses basically the same structure as Tal's answer.
a,b=map(int,input().split())
s='';p=1
while p<a:
 c=0;p+=1
 while a%p+b%p<1:a/=p;b/=p;c+=1
 if c:s+='%d^%d '%(p,c)
print(s)

It suffices to loop up to p=a-1, since we increment immediately to get p=a and a>=min(a,b). If b>a, there's no harm in trying useless values of p above a.
In 2.X, I think we could save characters by printing each piece as we get it rather than accumulating a string: if c:print'%d^%d'%(p,c),. Python 3, unfortunately, doesn't seem to have a compact way to print without a trailing newline.

PHP, 96
<?php
list(,$a,$b)=$argv;for($s=1;$s++<$a;$c&&print"$s^$c ")for($c=0;1>$a%$s+$b%$s;$a/=$s,$b/=$s)$c++;

We got almost exactly the same code! My one improvement is to combine p=0;g+=1 into one line by starting g at 1 instead, which lets you then do g<a rather than g<=a. I hope you grow to like python.

@xnor I missed your code. Indeed it's almost the same. I removed my python script. I hope i won't have to like python, I NEED braces

No need to remove your code, you came up with it yourself. I also came up with basically the game thing as Tal, so it looks like this is just what the Python golf converges to.

Pip, 41 bytes
Not a competing answer, since language is newer than question. But that GolfScript mark of 68 needed to come down.
Fi2,++a{p:0T$|g%i{++pg/:i}Ipx.:i.'^.p.s}x

Output ends in a space; if that's a problem, the following version is also 41 bytes (including the -s flag):
Fi2,++a{p:0T$|g%i{++pg/:i}IplAE:i.'^.p}l

Formatted, with explanations:
F i 2,++a {      For i in range(2,a+1); note ++ used to avoid parentheses in 2,(a+1)
  p:0            p will store the greatest power of i that divides both numbers
  T $+(g%i) {    Loop till the sum of g%i is nonzero, where g is a list initialized
                  from cmdline args
    ++p          As long as g%i is [0 0], increment p...
    g/:i         ...and divide both numbers in g by i
  }
  I p            If p is nonzero, i went into both numbers at least once
    x.:i.'^.p.s  Append i^p and a space to the result
}
x                Print the result

Pip, unlike GolfScript, CJam, et al. is an imperative language with infix operators; it also takes some inspiration from array-programming languages. This task nicely displays both paradigms at work.
(Note that the 2015-4-20 commit is needed to run this, since I just fixed a couple of bugs.)

Python 2 - 262 bytes
n,m=input(),input()
f=lambda i:set(filter(lambda x:i%x<1,range(1,i+1)))
g=max(f(n)&f(m))
p=[]
while g-1:
 p+=[min(filter(lambda x:x>1 and x%2!=(x==2)and not any(map(lambda y:x%y<1,range(2,x))),f(g)))]
 g/=p[-1]
print ' '.join(`a`+^+`p.count(a)`for a in set(p))

Line 6 needs work.

What about …`a`+'^'+`f.count(a)`…?

I have no idea how I missed that. Jeez. Thanks.

Groovy : 174 chars
This is a port of Geobits' solution to Groovy 2.2.1:
int i=1, n=args[0]as int, m=args[1]as int;s=n>m?n:m+1;f=new int[s];while(m>=++i||n>i){if(n%i+m%i<1){f[i]++;n/=i;m/=i--;}};(s-1).times{y=it+1;x=f[y];print"${x>0?"$y^$x ":""}"}

Here is the ungolfed version:
int i = 1, n = args[0] as int, m = args[1] as int

s = n>m?n:m+1
f = new int[s]

while (m>=++i||n>i) {
    if (n%i+m%i<1) {
        f[i]++;n/=i;m/=i--;
    }
}
(s-1).times {
    y=it+1
    x=f[y]
    print"${x>0?"$y^$x ":""}"
}

Surprised you chose to port Geobits' solution instead of mine, as mine is 56 characters shorter

R: 139
a=scan();q=1:a[1];n=max(q[!a[1]%%q&!a[2]%%q]);m=rep(0,n);for(i in 2:n){while(!n%%i){m[i]=m[i]+1;n=n/i};if(m[i])cat(paste0(i,"^",m[i])," ")}

With indentations:
a=scan() #Take space-separated numeric input from stdin
q=1:a[1]
n=max(q[!a[1]%%q&!a[2]%%q]) #gcd
m=rep(0,n)
for(i in 2:n){
    while(!n%%i){ #prime factorization
        m[i]=m[i]+1
        n=n/i
        }
    if(m[i])cat(paste0(i,"^",m[i])," ")
    }

Usage:
> a=scan();q=1:a[1];n=max(q[!a[1]%%q&!a[2]%%q]);m=rep(0,n);for(i in 2:n){while(!n%%i){m[i]=m[i]+1;n=n/i};if(m[i])cat(paste0(i,"^",m[i])," ")}
1: 196 294
3:
Read 2 items
2^1  7^2


text:
Pitch dark (Earth Hour remembrance)
Your goal is simple: the program must turn the screen of your computer totally black.
After the program is started, the screen must quickly turn completely black, and remain so until the program is exited (any key, or alt+F4, mouse movement, etc.), after which things should turn back to normal. So shutting down the computer or turning the power of the monitor off is NOT allowed.
Not a single non-black pixel should be visible during this time, not even a blinking cursor.
The user should not do any preparation (moving the mouse outside the screen, disconnecting cables, etc. or user input after the program started), just start the program.
You can safely assume the computer has only one monitor attached. We also assume a standard desktop or notebook computer, because doing it on a specific device without a normal monitor would be too simple.
If you use any external resources (a black image, a GUI file, etc.) their size in bytes is added to your code size.
It's OK if it only works on one OS family, or if it requires opengl etc., but requiring a very specific hardware configuration is frowned upon.
Your source code must be written in a programming language, not just a configuration file some other program (like a screen saver) will use.

That won't work on screens with stuck pixels...

@IsmaelMiguel : you can safely assume a screen in perfect working condition. Otherwise we could object other questions in the style of "what if a transistor in my ALU is burned out and my computer cannot do any floating point math?" :)

What hardware can we assume is available on the computer?

@AJMansfield : assume a standard off-the shelf PC with a VGA/HDMI video card and common peripherals. As I don't have experience in mobile phones, I would like to remain in the world of personal computers, otherwise someone would surprise me with a singe instruction which turns off the screen of a specific brand of mobile phone.

Fun fact: on screens that use neither CRT nor dynamic contrast, this will use slightly more electricity!

real world application: Astronomy! http://lists.apple.com/archives/Carbon-dev/2008/May/msg00005.html

@minitech You might be right, but almost everyone has LED or LCD screens. LCD screens work by passing electricity behind the crystals. And LEDs are tiny LEDs inside. The black color on those can be made by turning off the LEDs.

@IsmaelMiguel: Oh, right, those fancy LED screens. My comment refers specifically to TN LCDs, the most common as far as standalone LCD monitors go, I believe.

All of the answers are automatically disqualified—one of my monitors has a pixel whose red value is always 255!

@TheGuywithTheHat see comment number 1

This appears to be one of the few questions on this site with a Latex answer !

Could HTML qualify?

Bash, 28 or 12
Assuming default installation of Ubuntu 12.04 LTS.
gnome-screensaver-command -a

Automatically starts the screensaver, which is a black screen by default.
Edit: As suggested by @Glenn Randers-Pehrson, here's one with 12 bytes
/*/*/gn*d -a

Note that this may not work if you have another file on your system that satisfies this name, say /tmp/1/gnd. But it's code-golf, who cares?

Check out my other bash answer if you don't use Gnome screensaver!

The kind of answer that makes you think: 'Why on earth didn't I think of that?'. :)

That's not really clearing the screen using bash.

"Your source code must be written in a programming language, not just a configuration file some other program (like a screen saver) will use."

@hannes karppila I did not change any configuration file that any other program will use. I only started another program, which most bash scripts do (unless written in pure bash)

@ace, Golfed: ///gn*d instead of gnome-screensaver-command will save about 16 bytes (idea by mniip)

Works perfectly for me.

But your script does use gnome-screensaver-command, and as the OP says "If you use any external resources (a black image, a GUI file, etc.) their size in bytes is added to your code size." you should add its size.

@Mr Lister so if my bash script uses echo, cat, clear etc., do I need to add their sizes as well? And in fact, since some consider this invalid, I came up with another answer, which I linked to, which does not involve calling a screensaver.

@ace Technically at least some of what you listed aren't programs that are being called.  They're shell built-ins, but I'd agree that gnome-screensaver-command is not an external resource.  I would consider it more equivalent to calling an external library in C (like using winsock2.h on Windows)

While I do have some doubts about your answer abiding the rules, I think this much stretching of the rules can be tolerated here.

Assembly (bootloader) 131 chars / 512 bytes compiled (actually smaller, but bootsector must be 512 bytes long.)
It is a simple boot loader. When computer starts, BIOS will load it from disk (floppy). Then it enters into graphics mode and just hangs. When user presses the power button, program will end and computer will enter to mode where is was before running program.
Tested with VirtualBox.
It will compile with nasm:
nasm -f bin file.asm -o start.img

Source code:
[BITS 16]
[ORG 0x7C00]
cli
mov AX,0x0
mov SS,AX
mov SP,0x9000
sti
mov AH,0x0
mov AL,0x13
int 0x10
times 510 - ($-$$) db 0
dw 0xAA55

How to run on VirtualBox: (compile using nasm), new VM, Type: Other, version: Other/Unknown, no hard drive. Next up go to the VM's settings, select Storage, right click in the list, and select "Add Floppy Controller". Mount the compiled img file to the floppy drive. Save, and then you can run it. Enjoy!

I wanted to do the same thing as a dos program, but you were faster. Basically the only thing I remember of assembler from waaay back :)

Can you please explain how it works?

Why the cli and sti? Moves to SS automatically disable interrupts for the duration of the next instruction, and AX won't be changed if an interrupt happens before MOV SS,AX. Also, why not MOV AX, 0x13 instead of two MOVs?

Younger me didn't know how to write code properly. Current me probably doesn't know either.

QBASIC (31)
SCREEN 7
WHILE INKEY$=""
WEND

@TheGuywithTheHat I finally found a use for my windows 3.1 vm.

Wow seeing that WEND brought back memories

@user973810 You mean QB64.

Java : 165
Simple Java, just creates a fullscreen black frame. To exit you have to Alt+Tab back to the console and Ctrl-C, but that seems simple enough.
import java.awt.*;class B{public static void main(String[]a){Frame f=new Frame();f.setExtendedState(6);f.setUndecorated(1>0);f.setBackground(Color.BLACK);f.show();}}

// line breaks below

import java.awt.*;
class B{
    public static void main(String[]a){
        Frame f=new Frame();
        f.setExtendedState(6);
        f.setUndecorated(1>0);
        f.setBackground(Color.BLACK);
        f.show();
    }
}

Applesoft ][ BASIC (17)
1 HGR2:GET X:TEXT

I don't think this is actually 17 bytes...I think it might be less.  If I remember correctly, Applesoft tokenized its keywords, so that each keyword was actually one byte...so this one may be significantly shorter.  It's +1 either way.

Bash - 57 26
C=/s*/*/*/*/b*ess;(A=$(cat $C);echo 0;cat;echo $A)|tee $C

On a laptop this will set the screen backlight brightness to 0 via /sys/class/backlight, on a tablet or phone this will set the screen led brightness to 0 via /sys/class/leds

“and remain so until the program is exited (any key, or alt+F4, mouse movement, etc.), after which things should turn back to normal”

Fn+F6, Fn+<up arrow> and many other key combinations fall into "any key" and "etc.", and those are one of the many to put the light back as it was.

@minitech Oh. Well, fixed...

This doesn't work at all for me. If I do "C=/s*////bess;(A=$(cat $C);echo 0;cat;echo $A)|tee $C" from the bash prompt I get cat: /s*////bess: No such file or directory
tee: /s*////bess: No such file or directory

@Lembik I would assume that you don't have any brightness controllers or those present are lacking drivers. Mind pastebinning find /sys/class/{backlight,leds}/*/ ?

@mnip find /sys/class/{backlight,leds}//
find: ‘/sys/class/backlight//’: No such file or directory
find: ‘/sys/class/leds/*/’: No such file or directory

@mnip find /sys/class/{backlight,leds}/
/sys/class/backlight/
/sys/class/leds/

I know this is code-golf but I couldn't resist.
Just make sure you don't have any browser windows open (in this case, Chrome);
Execute this PitchBlack.bat (31 24 bytes):
chrome --kiosk file:///1

If placed in the same directory of your Chrome.exe file, this batch will execute Chrome in kiosk mode and it will open a file called /1 (49 41 34 bytes) in fullscreen:
<body bgcolor=0 style=cursor:none>

Et voilà!
Total byte count: 80 72 58
Thanks to @ace :)
To exit the program, you must go for a classic ALT+F4; You don't actually have to do any preparation after the program starts (neither before, you just have to place /1 and the batch file), so it's fine with the rules.
Please note that if you get your cursor towards the screen borders, it may become visible. The OP didn't say this was not allowed, since

After the program is started, the screen must quickly turn completely black, and remain so until the program is exited (any key, or alt+F4, mouse movement, etc.), after which things should turn back to normal.

So this should be totally ok! :P

Maybe something like chrome --kiosk 'data:text/html,<style>body{background:#000;cursor:none;}</style>' can work without additional file?

Means when using file: shceme you get no URL bar visible, but with data: scheme there is URL bar?

On my system chromium-browser --kiosk 'data:text/html,<style>body{background:#000;cursor:none;}</style> starts almost-fullscreen Chromium with the black page without any bars.

Tested on Ubuntu and Chromium 34.0, it works with file:///1 if the html is saved as /1, and the html file can be shortened to <body bgcolor=0 style=cursor:none>

@ace great one! :D

I think you should use chrome in your answer rather than chromium

C# - 211 202 200 196 179 bytes
using System.Windows.Forms;class A{static void Main(){Cursor.Hide();new Form{BackColor=System.Drawing.Color.Black,WindowState=(FormWindowState)2,FormBorderStyle=0}.ShowDialog();}}

Hides the cursor and shows a full-screen black window. Can be closed with Alt+F4
Un-golfed code:
using System.Windows.Forms;
class A
{
    static void Main()
    {
        Cursor.Hide();
        new Form
        {
            BackColor = System.Drawing.Color.Black,
            WindowState = (FormWindowState)2, // FormWindowState.Maximized
            FormBorderStyle = 0 // FormBorderStyle.None
        }.ShowDialog();
    }
}

I don't need to cast to FormBorderStyle, because that's not necessary if the integer is 0.

You can replace System.Drawing.Color.Black, FormWindowState.Maximized, FormWindowState.Maximized and FormBorderStyle.None with their corresponding values.

@IsmaelMiguel: Thanks, I updated the FormWindowState and the FormBorderStyle! I couldn't update the Color, because that's not an enum.

Try Color.Black. It should work right away. Or BackColor=This.ForeColor, which MIGHT work too.

@IsmaelMiguel: The first doesn't work because I didn't add using System.Drawing;, and the second doesn't work because I set the variable values inside brackets.

Try using System; then new Windows.Forms.Form and BackColor=Drawing.Color.Black. It MIGHT work! And save a few bytes.

Nevermind, it will not help :S But I really like the solution.

@IsmaelMiguel: That doesn't work, and even if it would work, I wouldn't save bytes, because I would have to add Windows.Forms.Form before FormWindowState and before FormBorderStyle.

(It works in VB.NET!)

This sounds like a stupid question but I must ask it: Won't it work if instead of BackColor=System.Drawing.Color.Black you put BackColor="#FF000000"? That is the ARGB representation of the color as a string. I don't have the C# compiler to test it.

@IsmaelMiguel: No, that doesn't work.

How about new System.Drawing.Color? I think that should work, even considering alpha. Would save one character. =)

@minitech: No, that does not work: I got the default color instead of black.

You can use object initializer to save two more bytes. Just change new Form(){ to new Form{.

@ŞafakGür: Thanks, I updated my answer!

I think ShowDialog would work instead of Application.Run.

@KendallFrey: Indeed, that works. Thanks!

C# 175 171 167
class P{static void Main(){SendMessage(65535,274,61808,2);}[System.Runtime.InteropServices.DllImport("user32")]static extern int SendMessage(int a,int b,int c,int d);}

A lot of the answers here don't actually make the screen black: on an LCD screen, the backlight remains on and bleeds through, leaving you with a darkish grey.
This little snippet actually tells Windows to turn off the screen, the same as what the inactivity timer does (Note: this doesn't violate the "no power off" rule because it really just causes the monitor to go into standby. Most monitors will turn back on when input is resumed. Also, that rule's intention seems to be to make sure the program can turn it back on - see below.)
Move the mouse or press a key to turn the screen back on.
Monitor power off adapted from https://stackoverflow.com/a/713519/1030702

"So shutting down the computer or turning the power of the monitor off is NOT allowed."

@IsmaelMiguel I have provided my justification. "until the program is exited (any key, or alt+F4, mouse movement, etc.), after which things should turn back to normal. So shutting..." - the rule's intention has been satisfied. This will "turn it back on". Leaving aside the intention, it also satifies the literal meaning, since, despite Microsoft's terminology, this isn't really turning it off (timeouts on projectors, etc., aside), it's placing it into standby.

Python / Pygame 199 127 125 92
from pygame import*;display.set_mode((9,9),-1<<31);mouse.set_visible(0)
while 1:event.pump()

Thanks to some tips from ace.

Since ALT+F4 counts, I'd take also ^C counts, so you can skip a lot of bytes at the end.

For ^C to work you need to be focused on the terminal, and in the program the pygame window is always focused due to pygame.FULLSCREEN
Edit: One alternative would be to leave the program with no exit, which would require spamming the keyboard till your OS notices something is wrong.

You can save some bytes by using from pygame import* instead. Also, I don't think fill((0,0,0)) is necessary since the default color is black. Then you can remove s altogether. I don't think display.flip() is needed either. Also, use one space for indentation instead of 4 can save you more spaces. Finally, instead of FULLSCREEN and KEYDOWN, you can use their numeric values, namely -1<<31 (-2147483648) and 2 respectively.

Amiga assembly
ASM-One - 228 219 chars, 172 bytes compiled (168 bytes optimized)
It's been 20 years since I last coded a single line in Amiga assembly, so bear with me. :-)
The Amiga was a bit more involved than the PC in terms of setting up a blank screen, so tried to get rid of as much setup and teardown as possible. There's no disabling of interrupts or multitasking; no double WaitTOF; no view replacement; etc. I wouldn't even have written this for the quickest and dirtiest demo. Which means this:

is bad practice
may not be entirely safe
may not always work
even with those disclaimers, probably has stupid mistakes owing to 20 years of neglected assembly.

... although it's been tested on emulated A500 and A1200, with or without fast memory. Compiles to a standard executable. Mouse click exits.
l=$dff080
 move.l 4,a6
 lea g,a1
 jsr -408(a6)
 move.l d0,a1
 move.l 38(a1),d4
 jsr -412(a6)
 move.l #c,l
w:btst #6,$bfe001
 bne w
 move.l d4,l
 rts
g:dc.b "graphics.library",0
 SECTION d,DATA_C
c:dc 256,512,384,0,-1,-2

Less golfed:
COP1LC equ $dff080

    move.l  $4, a6          ; ExecBase
    lea     gfxname, a1
    jsr     -408(a6)        ; OpenLibrary (old, hence no need for clearing d0)
    move.l  d0, a1
    move.l  38(a1), d4      ; store copper list
    jsr     -414(a6)        ; CloseLibrary
                            ; Yeah, if I had a penny for the times I saw that left out
                            ; but I just... can't...

    move.l  #copper,COP1LC  ; write copper list

wait:
    btst    #6, $bfe001     ; Check mouse click
    bne     wait

    move.l  d4, COP1LC      ; restore copper list
    rts

gfxname:
    dc.b    "graphics.library", 0

    SECTION data, DATA_C
copper:
    dc.w $0100, $0200       ; disable bitplanes
    dc.w $0180, $0000       ; color 0 = black
    dc.w $ffff, $fffe       ; end

Aaaah, the memories! Love it!

Yeah, this was more of an excuse for a nostalgia trip than a real attempt at code golf - Amiga assembly will rarely compete with Perl or Python in terms of character count. Although I was a bit surprised it couldn't beat C# or Java. :)

TI-BASIC, 7 6
Shade(Ymin,Ymax

Works both in the terminal (home screen) or as a program. Pressing ON or most other buttons returns to the terminal/home screen.

Can be one byte smaller (and work even if the graph screen window is changed) as Shade(Ymin,Ymax.

@ThomasKwa You're right, thanks for the tip!

sh/X11 on Arch Linux, 26
b=/b*/*ht;$b =0;read;$b =7

you can probably shave a few chars with an alias and maybe using -set for both

Use xbacklight = 0 and xbacklight + 7.

29 bytes: x=xbacklight;$x +0;read;$x +7

@nyuszika7h: Thanks! (Got it to 28, too!)

Bash, 37
Uses unclutter to hide the mouse pointer and a fullscreen session of xterm to black the screen. The cursor will reappear for a moment if you move it, but if you leave it alone the screen will be black until you press Ctrl+C.
It will take a few seconds for the mouse cursor to disappear (as long as you don't move it). If this isn't fast enough, add the -grab option to unclutter for an additional 6 chars.
unclutter&xterm -fu -bg black -e yes ''

WARNING:  this will leave a process of unclutter running even after you press Ctrl+C, use killall unclutter to stop it.
Explanation
unclutter & launches unclutter. The & is there so we can get on with the next command instead of waiting for this one to terminate.
xterm -fullscreen launches XTerm, whose background is black by default.
The -e yes '' option causes XTerm to run yes '', thereby printing the empty string forever. This serves to hide the terminal cursor, and also provides the Ctrl+C functionality.

Screen gets completely white in my system.

@Vi. that means your XTerm background colour is white.

You can abbreviate "-fullscreen" to "-fu", and use "-bg black" to force black background color regardless of user preferences.

You can remove the spaces around & to save 2 bytes.

Bash, 31 (or 52)
On a TTY, use the following script (assuming your default TTY background is black, which is true at least for Ubuntu 12.04 LTS):
setterm -foreground black
clear

Your TTY would still be fully functional even after using  this script :)
If this isn't allowed, use the following (52 bytes):
x='setterm -foreground'
$x black
clear
read
$x white

And press Enter to terminate the script.
Special thanks to @nyuszika7h.

For the second case: x='setterm -foreground';$x black;clear;read;$x white (52 bytes).

Commodore 64 (16 bytes)
ROL $A903
BRK
STA $D020
STA $D011
JSR $FF8A
JMP ($032C)

It has been more than 20 years since I used Turbo Assembler, so I can only provide source for use in VICE's monitor. Assemble this at $032C and save[1] through $033B. Reset and LOAD"PITCHDARK",8,1. Hit good ol' Runstop+Restore[2] to get back to normal.
How does it work?
Here's the true source:
032C 2E 03      .BY 2E 03
032E A9 00      LDA #$00
0330 8D 20 D0   STA $D020   ; set border color
0333 8D 11 D0   STA $D011   ; set VIC blanking mode
0336 20 15 FD   JSR $FF8A   ; reset the vectors we trampled
0339 6C 2C 03   JMP ($032C) ; call the real CLALL

$032C is the kernal CLALL or "Close All Channels And Files" vector. As part of its cleanup, the BASIC LOAD command does a CLR which in turn calls CLALL. We replace the CLALL vector with a pointer to our own routine immediately after the vector. We set the border to black and cover the screen with the border, and then call RESTOR at $FF8A. The last vector replaced by RESTOR is SAVE at $0332-0333 which means the last 8 bytes are undisturbed. We then exit via the restored CLALL vector to continue LOAD's execution.
Thanks for this, it was fun trip down memory lane, relearning how to do an autorun program :)
[1] use save and not bsave so that load with ,1 works correctly
[2] Escape + PageUp in x64, probably.

ZX Spectrum Basic (29 bytes)
1 FOR x=0 TO 255
2 FOR y=0 TO 175
3 PLOT x,y
4 NEXT y
5 NEXT x

Iterates over the screen, plotting black pixels which are automatically cleared when the program finishes.
The ZX Spectrum's edition of basic uses single bytes as commands and no newlines, if counting displayed characters you get 61 chars.

Lua + LÖVE (50)
love.mouse.setVisible()love.window.setFullscreen""

Both functions are supposed to take a boolean argument, yet this works.

Processing, 113
void setup(){noCursor();size(displayWidth, displayHeight);background(0);}boolean sketchFullScreen(){return true;}

I tried putting the code above onto draw() to save some bytes, but it didn't work. Press Alt-F4 to quit.

QBasic, 9 bytes
CLS:SLEEP

CLS clears the screen, SLEEP without any arguments holds execution until a key is pressed.

SmileBASIC, 15 bytes
XSCREEN 4
EXEC.

Pressing START or SELECT will end the program.
XSCREEN 4 sets the display mode to show a 320*480 image spanning both screens. This should clear everything, so an ACLS is not required. EXEC. makes the code repeat by constantly running the program in slot 0.
I wasn't able to do XSCREEN 4EXEC. because you can't have a number directly before E

Sinclair BASIC - 28 chars
BORDER 0:PAPER 0:CLS:PAUSE 0

The thing about Sinclair BASIC was each keyword had it's own character code (taking up one byte), so this would actually take up 13 bytes including spaces.

Does this return the screen to normal after finishing?

@kitcar2000 - Thinking about it, no. I'd probably add ":NEW" at the end as a quick and dirty reset, taking it up to 32 chars/15 bytes

I think that it is only 10 bytes (12 with :NEW) as the commands are single bytes rather than a collection of characters.

SmileBASIC, 23 bytes
Runs forever until the program is force-killed with START or SELECT. This makes both screens completely black, going so far to disable 3D (thus turning off the 3D LED on o3DS.)
ACLS:XSCREEN 3@L GOTO@L

Most POSIX compatible shells (at least bash and zsh), 21
Needs to be run on a tty
tput civis;clear;read

First command hides the cursor, second command clears the screen (duh) and third command reads a line of text

BASH - 14 chars
pmset sleepnow does the job!
(typed into my Mac's Terminal)

You should specify the OS and/or other prerequisites in your answer.

@ace answer edited :)

Doesn't sleep shut the monitor down?

Bash: 48 characters
eval xrandr\ --output\ DP1\ --{off,auto}\;read\;

CW because not clear whether it qualifies due to the way it works:

The produced black screen is real power saving: it cuts off information sending to display 1.
Many computer displays when detect signal loss, will temporarily or periodically show their own notice.

(Note that DP1 is the first connected display. If you have a laptop, its embedded display is eDP1.)

HTML Application (.hta), 102 bytes
<HTA:APPLICATION CAPTION=no innerborder=0 border=dialog scroll=0 windowstate=maximize><body bgcolor=0>

TI-80 BASIC, 5 bytes
ZOOM OUT
ZOOM OUT
GRIDON

Chip-8, 0 bytes

[T]he original Chip-8 interpreter began execution from 0x01FC. The interpreter includes two permanent Chip-8 instructions at this location that are always executed at the start of every programme. The first of these, 0x00E0, clears the display RAM by setting all the bits to zero. The second, 0x004B, calls a machine language routine within the interpreter that switches the VIP’s display on.

Source: http://laurencescotford.co.uk/?p=75

source: Stack Exchange

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

sort: votes


text:
Tips for golfing in LiveScript
What general tips do you have for golfing in LiveScript? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to LiveScript (e.g. "remove comments" is not an answer). Please post one tip per answer.

Agh. That’s a really annoying name for a language. JavaScript was LiveScript originally.

@minitech It was actually in part inspired by JavaScript's former name.

Take advantage of curried functions and Prelude.ls
If the function is already curried, it can be much shorter overall. Also, Prelude.ls is the standard library, and its functions are often very useful. This means, unless otherwise specified, this library is 100% allowed. Examples:
f=->[1 to &0].reduce (*) # space required
f=->product [1 to &0]

s=(.reduce (+))
s=sum                    # better yet, avoid defining this when possible

d=(.map (*2))
d=map (*2)               # Sometimes even shorter than native methods

r=->&0.reduce (-&1-)
r=->fold1 (-&1-),&0      # Equal if starting value is required.

a.=sort!
a=sort a                 # sometimes the same length

a.=sort ->&1.length-&0.length # space before arrow required
a.=sort over (-),(.length)    # slightly more functional
a=sortBy (.length)            # specific builtin, always prefer CamelCase

Positional function arguments
In LiveScript, & is a shorthand for arguments. arguments[0] can be shortened to &[0], which can be shortened to &.0, which in turn can be shortened to &0.
Before:
f=(x,y)->x+y

After:
f=->&0+&1

.n over [n], \n over ['n'], etc.
This won't work for computed indices and members, but with static ones, it shaves bytes. Examples:
f[0]
f.0

f['str']
f\str

f['str with spaces']
f'str with spaces'

This will not work with other literals, such as RegExps, booleans, null, void, etc.

Use partial functions when possible (with discretion)
Partial functions can drastically shorten many operations. Examples:
f=->it^2
f=(^2)

s=->&0.length==&1.length
s=over(==),(.length)

It isn't always better, though. Example:
# [[a, b], [c, d], [e, f]] -> (a+b)*(c+d)*(e*f)
f=(|>map sum|>product)
f=product map sum # these are actually curried

it instead of explicit function argument
If you have a function with a single argument and you only refer to it at most twice, use it instead.
Before:
f=(x)->x+x

After:
f=->it+it

I know this isn't the point, but this specific example would be best written as f=(*2).

Short form of switch
Use | instead of case and  |_ instead of default. Also, pipes themselves terminate statements.
Before:
switch x;case 1=>f;case 2=>g;default=>h

After:
switch x|1=>f|2=>g|_=>h

Avoid explicit commas and dots
This:
foo(1, 2, 3).bar

can be just:
foo(1 2 3)bar

Use the shortest function syntax possible
this:
->&0+&1

can be written:
(+)

and this:
->it.foo - it.bar

can be written:
(.foo- it.bar) # notice the dash position

I just wrote a more detailed answer on this (and the goal is to use the shortest number of bytes)

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


text:
Super speedy totient function
The goal is simple: calculate the totient function for as many numbers as you can in 10 seconds and sum the numbers.
You must print your result at the end and you must actually calculate it. No automated totient function is allowed, but bignum libraries are. You have to start at 1 and count up all the integers consecutively. You are not allowed to skip numbers.
Your score is how many numbers your program can calculate on your machine / how many my program can calculate on your machine. My code is a simple program in C++ (optimizations off), hopefully you can run it.
Important properties you could use!

if gcd(m,n) = 1, phi(mn) = phi(m) * phi(n)
if p is prime, phi(p) = p - 1 (for p < 10^20)
if n is even, phi(2n) = 2 phi(n)
others listed in first link

My code
#include <iostream>
using namespace std;

int gcd(int a, int b)
{
    while (b != 0)
    {
        int c = a % b;
        a = b;
        b = c;
    }
    return a;
}

int phi(int n)
{
    int x = 0;
    for (int i=1; i<=n; i++)
    {
        if (gcd(n, i) == 1)
            x++;
    }
    return x;
}

int main()
{
    unsigned int sum = 0;
    for (int i=1; i<19000; i++) // Change this so it runs in 10 seconds
    {
        sum += phi(i);
    }
        cout << sum << endl;
        return 0;
}

Maybe you might want to add that the input numbers should be consecutive integers. Otherwise I might be tempted to calculate the totient function for powers of 2 only.

Can I do 1, 3, 5, 2, 4 or the like?

Maybe it should be added that only one thread allowed or use CPUtime if the base code doesn't use, otherwise more core better score

Nimrod: ~38,667 (580,000,000/15,000)
This answer uses a pretty simple approach. The code employs a simple prime number sieve that stores the prime of the smallest prime power in each slot for composite numbers (zero for primes), then uses dynamic programming to construct the totient function over the same range, then sums the results. The program spends virtually all its time constructing the sieve, then calculates the totient function in a fraction of the time. It looks like it comes down to constructing an efficient sieve (with the slight twist that one also has to be able to extract a prime factor for composite numbers from the result and has to keep memory usage at a reasonable level).
Update: Improved performance by reducing memory footprint and improving cache behavior. It's possible to squeeze out 5%-10% more performance, but the increase in code complexity is not worth it. Ultimately, this algorithm primarily exercises a CPU's von Neumann bottleneck, and there are very few algorithmic tweaks that can get around that.
Also updated the performance divisor since the C++ code wasn't meant to be compiled with all optimizations on and nobody else did it. :)
Update 2: Optimized sieve operation for improved memory access. Now handling small primes in bulk via memcpy() (~5% speedup) and skipping multiples of 2, 3, and 5 when sieving bigger primes (~10% speedup).
C++ code: 9.9 seconds (with g++ 4.9)
Nimrod code: 9.9 seconds (with -d:release, gcc 4.9 backend)
proc handleSmallPrimes(sieve: var openarray[int32], m: int) =
  # Small primes are handled as a special case through what is ideally
  # the system's highly optimized memcpy() routine.
  let k = 2*3*5*7*11*13*17
  var sp = newSeq[int32](k div 2)
  for i in [3,5,7,11,13,17]:
    for j in countup(i, k, 2*i):
      sp[j div 2] = int32(i)
  for i in countup(0, sieve.high, len(sp)):
    if i + len(sp) <= len(sieve):
      copyMem(addr(sieve[i]), addr(sp[0]), sizeof(int32)*len(sp))
    else:
      copyMem(addr(sieve[i]), addr(sp[0]), sizeof(int32)*(len(sieve)-i))
  # Fixing up the numbers for values that are actually prime.
  for i in [3,5,7,11,13,17]:
    sieve[i div 2] = 0

proc constructSieve(m: int): seq[int32] =
  result = newSeq[int32](m div 2 + 1)
  handleSmallPrimes(result, m)
  var i = 19
  # Having handled small primes, we only consider candidates for
  # composite numbers that are relatively prime with 31. This cuts
  # their number almost in half.
  let steps = [ 1, 7, 11, 13, 17, 19, 23, 29, 31 ]
  var isteps: array[8, int]
  while i * i <= m:
    if result[i div 2] == 0:
      for j in 0..7: isteps[j] = i*(steps[j+1]-steps[j])
      var k = 1 # second entry in "steps mod 30" list.
      var j = 7*i
      while j <= m:
        result[j div 2] = int32(i)
        j += isteps[k]
        k = (k + 1) and 7 # "mod 30" list has eight elements.
    i += 2

proc calculateAndSumTotients(sieve: var openarray[int32], n: int): int =
  result = 1
  for i in 2'i32..int32(n):
    var tot: int32
    if (i and 1) == 0:
      var m = i div 2
      var pp: int32 = 2
      while (m and 1) == 0:
        pp *= 2
        m = m div 2
      if m == 1:
        tot = pp div 2
      else:
        tot = (pp div 2) * sieve[m div 2]
    elif sieve[i div 2] == 0: # prime?
      tot = i - 1
      sieve[i div 2] = tot
    else:
      # find and extract the first prime power pp.
      # It's relatively prime with i/pp.
      var p = sieve[i div 2]
      var m = i div p
      var pp = p
      while m mod p == 0 and m != p:
        pp *= p
        m = m div p
      if m == p: # is i a prime power?
        tot = pp*(p-1)
      else:
        tot = sieve[pp div 2] * sieve[m div 2]
      sieve[i div 2] = tot
    result += tot

proc main(n: int) =
  var sieve = constructSieve(n)
  let totSum = calculateAndSumTotients(sieve, n)
  echo totSum

main(580_000_000)

Epic! +1. Nimrod's starting to get more popular ;3

Wait. Woah. I'm upvoting your other answer. :P

Is Nimrod a cross between Python and C?

Nimrod was recently renamed to Nim; while it borrows Python's syntactic style, the semantics are different, and unlike C, it is memory-safe (unless you use unsafe features) and has garbage collection.

Java, score ~24,000 (360,000,000 / 15,000)
The java code below does calculation of the totient function and the prime sieve together. Note that depending on your machine you have to increase the initial/maximum heap size (on my rather slow laptop I had to go up to -Xmx3g -Xms3g).
public class Totient {

    final static int size = 360000000;
    final static int[] phi = new int[size];

    public static void main(String[] args) {
        long time = System.currentTimeMillis();
        long sum = 0;

        phi[1] = 1;
        for (int i = 2; i < size; i++) {
            if (phi[i] == 0) {
                phi[i] = i - 1;
                for (int j = 2; i * j < size; j++) {
                    if (phi[j] == 0)
                        continue;

                    int q = j;
                    int f = i - 1;
                    while (q % i == 0) {
                        f *= i;
                        q /= i;
                    }
                    phi[i * j] = f * phi[q];
                }
            }
            sum += phi[i];
        }
        System.out.println(System.currentTimeMillis() - time);
        System.out.println(sum);
    }
}

Nimrod: ~2,333,333 (42,000,000,000/18,000)
This uses an entirely different approach from my previous answer. See comments for details. The longint module can be found here.
import longint

const max = 500_000_000

var ts_mem: array[1..max, int]

# ts(n, d) is defined as the number of pairs (a,b)
# such that 1 <= a <= b <= n and gcd(a,b) = d.
#
# The following equations hold:
#
# ts(n, d) = ts(n div d, 1)
# sum for i in 1..n of ts(n, i) = n*(n+1)/2
#
# This leads to the recurrence:
# ts(n, 1) = n*(n+1)/2 - sum for i in 2..n of ts(n, i)
#
# or, where ts(n) = ts(n, 1):
# ts(n) = n*(n+1)/2 - sum for i in 2..n of ts(n div i)
#
# Note that the large numbers that we deal with can
# overflow 64-bit integers.

proc ts(n, gcd: int): int =
  if n == 0:
    result = 0
  elif n == 1 and gcd == 1:
    result = 1
  elif gcd == 1:
    result = n*(n+1) div 2
    for i in 2..n:
      result -= ts(n, i)
  else:
    result = ts(n div gcd, 1)

# Below is the optimized version of the same algorithm.

proc ts(n: int): int =
  if n == 0:
    result = 0
  elif n == 1:
    result = 1
  else:
    if n <= max and ts_mem[n] > 0:
      return ts_mem[n]
    result = n*(n+1) div 2
    var p = n
    var k = 2
    while k < n div k:
      let pold = p
      p = n div k
      k += 1
      let t = ts(n div pold)
      result -= t * (pold-p)
    while p >= 2:
      result -= ts(n div p)
      p -= 1
    if n <= max:
      ts_mem[n] = result

proc ts(n: int128): int128 =
  if n <= 2_000_000_000:
    result = ts(n.toInt)
  else:
    result = n*(n+1) div 2
    var p = n
    var k = 2
    while k < n div k:
      let pold = p
      p = n div k
      k += 1
      let t = ts(n div pold)
      result = result - t * (pold-p)
    while p >= 2:
      result = result - ts(n div p)
      p = p - 1

echo ts(42_000_000_000.toInt128)

Ladies and gentlemen, this is what I call wizardry.

Great approach for calculating the sum directly, but unfortunately it does not calculate the totient function for as many numbers as you can which is the challenge given above. Your code actually calculates results (not even the result of the totient function) for only several thousand numbers (approx. 2*sqrt(n)) which makes for a much lower score.

C#: 49,000 (980,000,000 / 20,000)
https://codegolf.stackexchange.com/a/26800 "Howard's code".
But modified, phi values are computed for odd integers.
using System;
using sw = System.Diagnostics.Stopwatch;
class Program
{
    static void Main()
    {
        sw sw = sw.StartNew();
        Console.Write(sumPhi(980000000) + " " + sw.Elapsed);
        sw.Stop(); Console.Read();
    }

    static long sumPhi(int n)  // sum phi[i] , 1 <= i <= n
    {
        long s = 0; int[] phi;
        if (n < 1) return 0; phi = buildPhi(n + 1);
        for (int i = 1; i <= n; i++) s += getPhi(i, phi);
        return s;
    }

    static int getPhi(int i, int[] phi)
    {
        if ((i & 1) > 0) return phi[i >> 1];
        if ((i & 3) > 0) return phi[i >> 2];
        int z = ntz(i); return phi[i >> z >> 1] << z - 1;
    }

    static int[] buildPhi(int n)  // phi[i >> 1] , i odd , i < n
    {
        int i, j, y, x, q, r, f; int[] phi;
        if (n < 2) return new int[] { 0 };
        phi = new int[n / 2]; phi[0] = 1;
        for (j = 2, i = 3; i < n; i *= 3, j *= 3) phi[i >> 1] = j;
        for (x = 4, i = 5; i <= n >> 1; i += x ^= 6)
        {
            if (phi[i >> 1] > 0) continue; phi[i >> 1] = i ^ 1;
            for (j = 3, y = 3 * i; y < n; y += i << 1, j += 2)
            {
                if (phi[j >> 1] == 0) continue; q = j; f = i ^ 1;
                while ((r = q) == i * (q /= i)) f *= i;
                phi[y >> 1] = f * phi[r >> 1];
            }
        }
        for (; i < n; i += x ^= 6)  // primes > n / 2
            if (phi[i >> 1] == 0)
                phi[i >> 1] = i ^ 1;
        return phi;
    }

    static int ntz(int i)  // number of trailing zeros
    {
        int z = 1;
        if ((i & 0xffff) == 0) { z += 16; i >>= 16; }
        if ((i & 0x00ff) == 0) { z += 08; i >>= 08; }
        if ((i & 0x000f) == 0) { z += 04; i >>= 04; }
        if ((i & 0x0003) == 0) { z += 02; i >>= 02; }
        return z - (i & 1);
    }
}

New score: 61,000 (1,220,000,000 / 20,000)
In "App.config" I had to add "gcAllowVeryLargeObjects enabled=true".
    static long sumPhi(int n)
    {
        int i1, i2, i3, i4, z; long s1, s2, s3, s4; int[] phi;
        if (n < 1) return 0; phi = buildPhi(n + 1); n -= 4; z = 2;
        i1 = 1; i2 = 2; i3 = 3; i4 = 4; s1 = s2 = s3 = s4 = 0;
        if (n > 0)
            for (; ; )
            {
                s1 += phi[i1 >> 1];
                s2 += phi[i2 >> 2];
                s3 += phi[i3 >> 1];
                s4 += phi[i4 >> z >> 1] << z - 1;
                i1 += 4; i2 += 4; i3 += 4; i4 += 4;
                n -= 4; if (n < 0) break;
                if (z == 2)
                {
                    z = 3; i4 >>= 3;
                    while ((i4 & 3) == 0) { i4 >>= 2; z += 2; }
                    z += i4 & 1 ^ 1;
                    i4 = i3 + 1;
                }
                else z = 2;
            }
        if (n > -4) s1 += phi[i1 >> 1];
        if (n > -3) s2 += phi[i2 >> 2];
        if (n > -2) s3 += phi[i3 >> 1];
        if (n > -1) s4 += phi[i4 >> z >> 1] << z - 1;
        return s1 + s2 + s3 + s4;
    }

    static int[] buildPhi(int n)
    {
        int i, j, y, x, q0, q1, f; int[] phi;
        if (n < 2) return new int[] { 0 };
        phi = new int[n / 2]; phi[0] = 1;
        for (uint u = 2, v = 3; v < n; v *= 3, u *= 3) phi[v >> 1] = (int)u;
        for (x = 4, i = 5; i <= n >> 1; i += x ^= 6)
        {
            if (phi[i >> 1] > 0) continue; phi[i >> 1] = i ^ 1;
            for (j = 3, y = 3 * i; y < n; y += i << 1, j += 2)
            {
                if (phi[j >> 1] == 0) continue; q0 = j; f = i ^ 1;
                while ((q1 = q0) == i * (q0 /= i)) f *= i;
                phi[y >> 1] = f * phi[q1 >> 1];
            }
        }
        for (; i < n; i += x ^= 6)
            if (phi[i >> 1] == 0)
                phi[i >> 1] = i ^ 1;
        return phi;
    }

Python 3: ~24000 (335,000,000 / 14,000)
My version is a Python port of Howard's algorithm. My original function was a modification of an algorithm introduced in this blogpost.
I'm using Numpy and Numba modules to speed up the execution time. Note that normally you don't need to declare the types of the local variables (when using Numba), but in this case I wanted to squeeze the execution time as much as possible.
Edit: combined constructsieve and summarum functions into a single function.
C++: 9.99s (n = 14,000);
Python 3: 9.94s (n = 335,000,000)
import numba as nb
import numpy as np
import time

n = 335000000

@nb.njit("i8(i4[:])", locals=dict(
    n=nb.int32, s=nb.int64, i=nb.int32,
    j=nb.int32, q=nb.int32, f=nb.int32))

def summarum(phi):
    s = 0

    phi[1] = 1

    i = 2
    while i < n:
        if phi[i] == 0:
            phi[i] = i - 1

            j = 2

            while j * i < n:
                if phi[j] != 0:
                    q = j
                    f = i - 1

                    while q % i == 0:
                        f *= i
                        q //= i

                    phi[i * j] = f * phi[q]
                j += 1
        s += phi[i]
        i += 1
    return s

if __name__ == "__main__":
    s1 = time.time()
    a = summarum(np.zeros(n, np.int32))
    s2 = time.time()

    print(a)
    print("{}s".format(s2 - s1))

You should give proper credit when you copy code from other users.

Updated with proper credits!

Here is my Python implementation that seems to be able to crank out ~60000 numbers in 10seconds. I am factorizing numbers using the pollard rho algorithm and using the Rabin miller primality test.
from Queue import Queue
import random

def gcd ( a , b ):
    while b != 0: a, b = b, a % b
    return a

def rabin_miller(p):
    if(p<2): return False
    if(p!=2 and p%2==0): return False
    s=p-1
    while(s%2==0): s>>=1
    for _ in xrange(10):
        a=random.randrange(p-1)+1
        temp=s
        mod=pow(a,temp,p)
        while(temp!=p-1 and mod!=1 and mod!=p-1):
            mod=(mod*mod)%p
            temp=temp*2
        if(mod!=p-1 and temp%2==0): return False
    return True

def pollard_rho(n):
    if(n%2==0): return 2;
    x=random.randrange(2,1000000)
    c=random.randrange(2,1000000)
    y=x
    d=1
    while(d==1):
        x=(x*x+c)%n
        y=(y*y+c)%n
        y=(y*y+c)%n
        d=gcd(x-y,n)
        if(d==n): break;
    return d;

def primeFactorization(n):
    if n <= 0: raise ValueError("Fucked up input, n <= 0")
    elif n == 1: return []
    queue = Queue()
    factors=[]
    queue.put(n)
    while(not queue.empty()):
        l=queue.get()
        if(rabin_miller(l)):
            factors.append(l)
            continue
        d=pollard_rho(l)
        if(d==l):queue.put(l)
        else:
            queue.put(d)
            queue.put(l/d)
    return factors

def phi(n):

    if rabin_miller(n): return n-1
    phi = n
    for p in set(primeFactorization(n)):
        phi -= (phi/p)
    return phi

if __name__ == '__main__':

  n = 1
  s = 0

  while n < 60000:
    n += 1
    s += phi(n)
  print(s)

Very helpful solution, changing random.randrange(2,1000000) to random.getrandbits(8)+2 in pollard_rho and using math.gcd from the stdlib gave me large performance improvements with this algorithm. Using random.getrandbits might improve rabin_miller a bit, but less so than the other usage, but wasn't as cut and dry.

Matlab: 1464  = 26355867/ 18000
I can't test your code so I divided by 18000 as it represents the fastest computer of those who tested. I came to the score using this property:

if p is prime, phi(p) = p - 1 (for p < 10^20)

I mostly like that it is a one liner:
sum(primes(500000000)-1)

What about phi(p) for all non-prime p?

@Geobits I skipped those as the question does not mention which numbers you should use, as long as they are really calculated.

Ah, didn't notice that in the wording. Nice.

You didn't even post a score...

@qwr I can't run C++ and MATLAB on the same hardware, but I have made an estimate of the score.

...How is it possible to not have Matlab & C++ on the same computer?

@KyleKanos I can't install anything on the computer with MATLAB, and my licencse limits me from installing MATLAB on the computer where I use C++, however if you have both on the same computer feel free to update my score.

φ(2n) = 2n − 1
Σ φ(2i) = 2i − 1 for i from 1 to n
First, something to find times:
import os
from time import perf_counter

SEARCH_LOWER = -1
SEARCH_HIGHER = 1

def integer_binary_search(start, lower=None, upper=None, big_jump=1):
    if lower is not None and lower == upper:
        raise StopIteration # ?

    result = yield start

    if result == SEARCH_LOWER:
        if lower is None:
            yield from integer_binary_search(
                start=start - big_jump,
                lower=None,
                upper=start - 1,
                big_jump=big_jump * 2)
        else:
            yield from integer_binary_search(
                start=(lower + start) // 2,
                lower=lower,
                upper=start - 1)
    elif result == SEARCH_HIGHER:
        if upper is None:
            yield from integer_binary_search(
                start=start + big_jump,
                lower=start + 1,
                upper=None,
                big_jump=big_jump * 2)
        else:
            yield from integer_binary_search(
                start=(start + upper) // 2,
                lower=start + 1,
                upper=upper)
    else:
        raise ValueError('Expected SEARCH_LOWER or SEARCH_HIGHER.')

search = integer_binary_search(start=1000, lower=1, upper=None, big_jump=2500)
n = search.send(None)

while True:
    print('Trying with %d iterations.' % (n,))

    os.spawnlp(
        os.P_WAIT,
        'g++', 'g++', '-Wall', '-Wextra', '-pedantic', '-O0', '-o', 'reference',
        '-DITERATIONS=%d' % (n,),
        'reference.cpp')

    start = perf_counter()
    os.spawnl(os.P_WAIT, './reference', './reference')
    end = perf_counter()
    t = end - start

    if t >= 10.1:
        n = search.send(SEARCH_LOWER)
    elif t <= 9.9:
        n = search.send(SEARCH_HIGHER)
    else:
        print('%d iterations in %f seconds!' % (n, t))
        break

For the reference code, for me, that’s:

…
  Trying with 14593 iterations.
  64724364
  14593 iterations in 9.987747 seconds!

Now, Haskell:
import System.Environment (getArgs)

phiSum :: Integer -> Integer
phiSum n = 2 ^ n - 1

main :: IO ()
main = getArgs >>= print . phiSum . (2^) . read . head

It makes something with 2525224 digits in 0.718 seconds. And now I’m just noticing @Howard’s comment.

Can you post a score with the total consecutive numbers starting from 1 you managed to sum?

@qwr, that would be 0. If you want consecutive numbers, you should specify it in your question =)

I did. I've edited it already, I'll edit it again.

Python 2.7: 10.999 (165975/15090)
Pypy 2.3.1: 28.496 (430000/15090)
Some interesting methods I use:
Rabin-Miller Strong Pseudoprime Test - A primality test that provides an efficient probabilistic algorithm for determining if a given number is prime
Euler's product formula  - The product is over the distinct prime numbers dividing n

Code:
import math
import random

#perform a Modular exponentiation
def modular_pow(base, exponent, modulus):
    result=1
    while exponent>0:
        if exponent%2==1:
           result=(result * base)%modulus
        exponent=exponent>>1
        base=(base * base)%modulus
    return result

#Miller-Rabin primality test
def checkMillerRabin(n,k):
    if n==2: return True
    if n==1 or n%2==0: return False

    #find s and d, with d odd
    s=0
    d=n-1
    while(d%2==0):
        d/=2
        s+=1
    assert (2**s*d==n-1)

    #witness loop
    composite=1
    for i in xrange(k):
        a=random.randint(2,n-1)
        x=modular_pow(a,d,n)
        if x==1 or x==n-1: continue
        for j in xrange(s-1):
            composite=1
            x=modular_pow(x,2,n)
            if x==1: return False #is composite
            if x==n-1:
                composite=0
                break
        if composite==1:
            return False        #is composite
    return True                 #is probably prime

def findPrimes(n):              #generate a list of primes, using the sieve of eratosthenes

    primes=(n+2)*[True]

    for i in range(2,int(math.sqrt(n))+1):
        if primes[i]==True:
            for j in range(i**2,n+1,i):
                primes[j]=False

    primes=[i for i in range(2,len(primes)-1) if primes[i]==True]
    return primes

def primeFactorization(n,primes):   #find the factors of a number

    factors=[]

    i=0
    while(n!=1):
        if(n%primes[i]==0):
            factors.append(primes[i])
            n/=primes[i]
        else:
            i+=1

    return factors

def phi(n,primes):
    #some useful properties
    if (checkMillerRabin(n,10)==True):      #fast prime check
        return n-1

    factors=primeFactorization(n,primes)    #prime factors
    distinctive_prime_factors=set(factors)

    totient=n
    for f in distinctive_prime_factors:     #phi = n * sum (1 - 1/p), p is a distinctive prime factor
        totient*=(1-1.0/f);

    return totient

if __name__ == '__main__':

    s=0
    N=165975
    # N=430000
    primes=findPrimes(N)    #upper bound for the number of primes
    for i in xrange(1,N):
        s+=phi(i,primes)

    print "Sum =",s

Thanks fro the algorithms! It was the only one I could understand easily and is not brute force checking of counting co-primes.

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


text:
Challenge: compress co-occuring columns into cartesian product
This challenge is inspired by a problem I encountered recently out in the real-world, though ultimately I cheated and found a workaround.
Challenge
The input is a space-separated table of characters (each line is a row, and every line will have the same number of columns). Your challenge is to group together co-occurring column values and output a 'compressed' table, and there may be duplicate rows. Let's look at an example:
input:
A X I
B X I
A Y I
B X I
B Y I

output:
AB XY I

The output is parsed as the cartesian product between each column:
AB XY = A X, B X, A Y, B Y

The union of cartesian products of columns in each output row must exactly match the set of all unique input rows. In other words, no skipping input rows and no specifying input rows that don't exist!
For further exampling, note that if the third column contained anything other than I, this would be harder to compress:
input:
A X I
B Y I
A Y $
B X I
B Y I

output:
A X I
A Y $
B XY I

Rules

no non-standard libraries or calls to high-level compression functions. The spirit of the question is to write the algorithm yourself!
output must be in the same format as inputs (zipping your output files is cheating)
no hard-coding the answers of each test file. Your program needs to be able to handle arbitrary (correct) inputs.

Scoring (lowest wins)

Size of your program in bytes (you may count the name of the input as a single byte)
Plus the size (in bytes) of all of your output files on the given tests.
-10% bonus if you have the fastest program (as it runs on my machine). Speed will be measured as the average time on 10 randomly generated test cases using generate.py 6 8 4 6 5 (the same 10 files for each program of course)

Test Files
These files are generated with this python script. The answer keys aren't guaranteed to be the minimum compression - you may be able to do better!

Input 1, Answer Key 1, generated with python generate.py 5 10 4 6 5
Input 2, Answer Key 2, python generator.py 7 6 2 4 6
Input 3, Answer Key 3, ...edit: the numbers here were wrong

So... if a person takes the output generated by one of these programs, they should be able to recreate each unique row of data, and nothing more, correct?

And... do I need to use a similar compression form, or will any form work provided a person can follow an algorithm to generate each unique row of data and nothing more?  E.g., can my output for your example 2 look like 3:AXI|Y$;BXI|YI

Yes, all unique rows of input can be generated from the output (which is how the generate script works). And no you may not use a different format for the output. Standardization.

And "fastest program" on which benchmark file? The sum of the three given ones?

@rangu that sounds fair, but you should specify how many files as well as the generator parameters used for to get those random test files.

@rangu add that to the post please, then we can clean up the comments

This problem is known as Boolean tensor factorization. Finding the minimum number of output rows needed (Boolean tensor rank) is known to be NP-hard.

I was afraid of that.. Approximate solutions will still earn a better score than the naive approach

I'll start things off with the simplest possible answer.. According to my own specifications, the input file qualifies as a 'compression' of itself (albeit not a very efficient one).
Python: 22+3359+183735+239 with 10% bonus = 168619.5
print open('testfile').read()

This answer won't count for the 10% bonus once other answers are posted. That would be silly.

it should, unless someone writes something actually faster (assembly, anyone?)


text:
Duct tape can fix anything
Overview
This challenge was inspired by this StackOverflow Meta post.  In it, @hakre says:

I've seen a project really written by Stackoverflow (a noob copies together from SO here and SO there), attribution normally never is done which results in rights termination under CC. (sic)

Your mission is to make the most interesting program you can -- without ever writing a single line of code.  You can only use code which is already written for you, both in questions and answers from StackOverflow.  All you can do is duct tape it all together the best you can.  And of course, it's very important that we provide appropriate attribution so that we don't get our rights terminated.

Rules

You must include links to the questions/answers you used in your answer.
You may not modify the code you find, with the following exceptions:
a. You may rename variables, functions, and methods.  (This doesn't mean you can change a method invocation, by changing, say scanner.nextInt() to scanner.nextLine() and claiming that you're changing a method name.  The change must be in the definition or reference to the same entity.)
b. You may adjust indentation appropriately.
c. You can assume that the proper modules are loaded for the code snippets to work.  (e.g., import statements for Java and Python, using statements for C# and C++, and their equivalents in all languages)  If the code snippet includes the imports for you, you can move them to the top of the code.
d. If the language requires the code to be in some kind of method body to execute (e.g., public static void main(String[] args) for Java, static int Main(string[] args) for C#, and so on), you can wrap your code in the appropriate method.  But the contents of that main method must remain unmodified.
You must supply an explicit list of any variable/method/function/class rename-ings performed.
You can't take snippets of snippets (meaning if you take a code block from a post, you take the whole thing)
Provide a brief description of what the code does for people who aren't intimate with the language you're using.
Popularity contest, so the most upvotes wins!

Boring Five Minute Example (Python 3)
Description: Reads a bunch of log files from the current directory and randomizes the lines in them (exciting, right? This would totally win a popularity contest)
Source
import glob
import random

for file in glob.glob('log-*-*.txt'):
    # Etc.
    with open(file) as f:
        content = f.readlines()
        # shuffle the list in place
        random.shuffle(content)

        # print it
        print(content)

Legal Modifications

Renamed fname to file from link 1
Renamed b to content from link 2

Attributions

https://stackoverflow.com/a/3277516/1435657
https://stackoverflow.com/a/16737991/1435657
https://stackoverflow.com/a/4918520/1435657

I really like the idea, but I think this question would immensely benefit from limiting the scope to a particular task. That would a) inspire more creativity because you can't just copy together anything and b) it would leave open the possibility to reuse this (interesting) type of question later on in a different context. If you just leave it as "do whatever you want", all further questions like this will be duplicates. I'm afraid as it stands, I have to close-vote as "too broad" because it torpedoes possibly interesting future questions.

Not to mention that someone could just say, "Print "hello world" and be done

@m.buettner Hmm... fair enough.  I don't have any good ideas for what to limit the scope to, though, I'm afraid.

Couldn't I just take a Brainfuck program, and "reuse" the +-<>,.[] characters to form a new program?

@TheDoctor I doubt that that would win a popularity contest.

I should add, no I don't want this to become the next code-trolling, where everyone posts a "Add two numbers", "Split this string", with a "duct-tape-coding" tag. I think we can handle this more creatively than that. I would just like to leave some room for other interpretations of this kind of restricted-source competition.

@m.buettner I'm also not sure that CodeGolf.SE would necessarily benefit from lots of questions like this, for the same reasons you mention: why have "split a string using SO code", "get a random number from 1-100 using SO code", and so forth?  But that's just my opinion.  I'm far from a CodeGolf.SE pro. :)

I'm going to remove the random custom tag for now because the need for it hasn't been established (and it will very likely be unnecessary and add no value).

@marinus You can't reuse characters from a post.  You have to use the entire block of code.  So I don't think so, no. :)

I dunno, the "no snippets of snippets" rule seems like it could be a little too restricting. I know the intention is to stop them from just copying one character from a bunch of places to write anything they want, so why not change "no snippets of snippets", to "you can make snippets of snippets, but only if it consists of complete lines".

@B1KMusic I think the challenge becomes too easy if you can pull out any lines from any posts.  I think it's important that the "piecing together" remain the focal point of the challenge rather than rewarding a person who spends the time to look up 200 SO posts, takes a line from each of them, and makes a comprehensive program from it.  The latter makes the challenge both extremely trivial and, more importantly, extremely boring.

I agree that we need to be careful with flooding PPCG with questions like this, just because it's fun and novel. But I think a few genuinely different questions could come of this... like a maths-based, a graphics-based one, one that uses code-golf scoring and a polyglot challenge maybe. Hence, I'd prefer the scope to be limited. In terms of people just copying the challenge without anything substantial, I think it's the duty of the community to be a bit stricter in "closing as duplicate" when it comes to new challenge types.

C - one operation calculator
Let's have this for a start.
It's actually quite hard to find pieces of C programs that aren't whole programs. I had most trouble with declarations.
// http://stackoverflow.com/a/2911978 Block #1 (changed i to a)
static int a = 10;
// http://stackoverflow.com/a/2911978 Block #1 (changed i to b)
static int b = 10;
// http://stackoverflow.com/a/442647 Block #1 (changed c to op)
unsigned char op = (unsigned char)-1;
// http://stackoverflow.com/q/3711048 Inline block #1
int main()
// http://stackoverflow.com/a/14902422 Inline block #1
{
// http://stackoverflow.com/q/217074 Inline block #2 (changed i to a)
scanf("%d", &a)
// http://stackoverflow.com/a/23353870 Inline block #2
;
// http://stackoverflow.com/q/217074 Block #2 (changed c to op)
scanf("%c", &op)
// http://stackoverflow.com/a/23353870 Inline block #2
;
// http://stackoverflow.com/q/217074 Inline block #2 (changed i to b)
scanf("%d", &b)
// http://stackoverflow.com/a/23353870 Inline block #2
;
// http://stackoverflow.com/a/4173188 Block #2
int result = 0;
result = (op == '*') ? a * b : result;
result = (op == '/') ? a / b : result;
result = (op == '+') ? a + b : result;
result = (op == '-') ? a - b : result;
printf("%d",result);
// http://stackoverflow.com/a/3245525 Block #2
printf("\n");  /* prints newline */
// http://stackoverflow.com/q/4138649 Inline block #1
return 0;
// http://stackoverflow.com/a/14902422 Inline block #2
}

Takes a simple integral operation like 3+151 or 41/2 on stdin and outputs the result to stdout.

Interesting re-use of the same code block and renaming the variable twice.  I didn't even think of that!  +1