Wednesday, September 26, 2012

Solution to Project Euler Problem 10 - Find the sum of all the primes below two million

http://projecteuler.net/problem=10

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

Answer:   457143142877

Solution:

#!/usr/bin/perl -w
use strict;
use Math::Complex;
my (@primes,$ulimit,$stop);
$ulimit=2000000;
$stop=10001;
generate_prime();

sub generate_prime {
        my ($i,$j,$prime,$squareroot,$count);
        @primes=(2,3,5,7); #initial prime numbers
        my $sum=17;  #initial sum = 2+3+5+7
        #We know only 2 is the even prime numbers, hence skip all even numbers
        for ($i=9;$i<=$ulimit; $i+=2) {
                $prime=0;
                #Divide the number by all the prime numbers less than the square root
                $squareroot=sqrt($i);
                foreach $j (@primes) {
                        if ( $j > $squareroot ) {
                                last;
                        }
                        if (($i%$j) == 0) {
                                $prime=1;
                                last;
                        }
                }
                if ($prime == 0 ) {
                        print "The current prime number is: $i\n";
                        $sum+=$i;
                        print "sum till now: $sum \n";

                }
        }
}

6 comments:

Anonymous said...

buy nNZpOwAr [URL=http://www.camera--lenses.com/]canon 75-300 iii[/URL] with low price XtnwJlTy [URL=http://www.camera--lenses.com/ ] http://www.camera--lenses.com/ [/URL]

Anonymous said...

I am sure you will love coPsrUPv [URL=http://www.camera--lenses.com/]canon ef 75-300mm[/URL] and get big save OFGDLAoq [URL=http://www.camera--lenses.com/ ] http://www.camera--lenses.com/ [/URL]

Anonymous said...

sell FgYxraeb [URL=http://www.cheapguccireplica.tumblr.com/]gucci outlets[/URL] for less mRZjhwkj [URL=http://www.cheapguccireplica.tumblr.com/ ] http://www.cheapguccireplica.tumblr.com/ [/URL]

Anonymous said...

I'm sure the best for you wmaPyeSh [URL=http://www.replicalv.webs.com/]louis vuitton cheap[/URL] , for special offer eTgVqMef [URL=http://www.replicalv.webs.com/ ] http://www.replicalv.webs.com/ [/URL]

Anonymous said...

click ofvaZpQG [URL=http://www.cheapdesigner--handbags.weebly.com/]fake designer purses[/URL] online KyfkHzKh [URL=http://www.cheapdesigner--handbags.weebly.com/ ] http://www.cheapdesigner--handbags.weebly.com/ [/URL]

Anonymous said...

get cheap pdhWobBn [URL=http://www.cheapdesigner--handbags.weebly.com/]fake designer bags[/URL] to get new coupon WCvVyEdU [URL=http://www.cheapdesigner--handbags.weebly.com/ ] http://www.cheapdesigner--handbags.weebly.com/ [/URL]