javaprimescode-golf

Shortest-code for prime-calculation


The newspaper for the Computer Science-line at my school (called readme, it's norwegian, page 19) had a fun competition to write the shortest possible Java-code for the following problem.

Take in an integer (as a string in the first entry of a string array, since the Java main method only takes a string array) as an argument, and write out first all numbers below this number that are primes, and then all numbers that are not primes. The shortest code wins!

As an answer, I will post the shortest Java-code that won the competition. I wonder if the Stack Overflow Community can make a code that is shorter If you know Norwegian, you will see that you could've won a bottle of champagne if you had done it, but unfortunately the last submit date of the competition is over.

How would you have solved this problem?


Solution

  • I was already doing it in Haskell before you changed the title to "Java". Since this is a community wiki, here it is anyway.

    primes n = 
    let sieve (p:xs) = p : sieve [x | x<-xs, x `mod` p /= 0] in 
    let primes = takeWhile (<n) $ sieve [2..] in 
    ([0..n] \\ primes, primes)
    
    *Main> primes 20
    ([0,1,4,6,8,9,10,12,14,15,16,18,20],[2,3,5,7,11,13,17,19])
    

    (edit:) Shortening names and removing whitespace makes it 79 chars:

    p n=let s(p:xs)=p:s[x|x<-xs,x`mod`p/=0];r=takeWhile(<n)$s[2..]in(r,[0..n-1]\\r)
    

    here also the resulting pair's order is swapped, and n-1 is used, as per the spec.

    Using sub-optimal trial division brings it down to 50 chars:

    p n=partition(\k->all((>0).rem k)[2..k-1])[2..n-1]