Friday, January 2, 2009

Project Euler and PowerShell - Problem 10

Continuing on with Project Euler, I am momentarily skipping problems 8 (getting that big string into a numeric array still eludes me!) and 9 to quickly do problem 10.

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.

This is another brute force attack. I am sure there is a more efficient algorithm, but the following gets it done.
function isPrime
param ($number)
$isPrime = $true
if($number -lt 2) { $isPrime = $False}
if($number -gt 2 -and $number%2 -eq 0) {$isPrime = $False}
for($i=3;$i -le [math]::Sqrt($number);$i+=2)
if($number % $i -eq 0) { $isPrime = $False}

for($i=3; $i -lt $limit;$i+=2)
if( isPrime $i)
"{0}`t{1}" -f $i, $sum
While this generates the correct answer, it is painfully slow. I will be revisiting this one in an attempt to optimize it.

1 comment:

Anonymous said...

Thank you so much for this post, it was very insightful!
Reverse Phone Lookup also contains hundreds of cell phone and telecommunications articles and resources covering all aspects of cell phone safety, security, accessories and shopping.
Phone Number Trace Reverse Phone Lookup, Unknown Number Search - welcome to visit More Reviews.