OH noo, please not that again! Yeah, primes sigh. But they play a minor role here as a perfect victim to explain some other things. Would not advise to use the algorithm here to calculate them in real life. There are languages like Python, F#, Haskell etc. who have list comprehension on board. I was wondering how to do it in C#. Looked up some examples on the net and concoct my own here. See the
factors method on line 84 and the
primes method on line 109. What I like about this code is that it is so concise yet easy to comprehend.( That is I think it is :) )
PLINQ joins in as I use the
AsParallel() extension on line 111. You might as well add the
AsOrdered() extension. Parallel processors don't always deliver their tasks in order! Working parallel is not always advisable. Think of numbers less than 1000 or so. Calculate primes from 2 to 100000 and you're in business. Calculating all the primes up to 1234567 on my i7 four core machine in parallel, still takes about half an hour, while taking up 96% of total processor time(seen in Task Manager). Leave
.AsParallel().AsOrdered()out if you want to see the time difference. Enjoy. Any comments are always welcome.