Wednesday, 26 September 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";

                }
        }
}

1 comment:

  1. Jammin' Jars (Casino) Casino Tunica Hotel & Casino Tickets
    Jammin' Jars Casino Tunica Hotel & Casino Tunica is 밀양 출장샵 one of the 제주 출장마사지 few casinos in South 문경 출장마사지 Africa offering real money gaming 유로 스타 도메인 and live entertainment.Feb 20, 2022JamboMar 3, 2022Jambo 광양 출장마사지

    ReplyDelete