Post Reply 
 
Thread Rating:
  • 0 Votes - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Prime sum challenge
12-04-2009, 10:07 AM (This post was last modified: 12-04-2009 10:17 AM by codecaine.)
Post: #1
Prime sum challenge
What is the sum of all prime numbers below 5000?
Answer is: 1548136

Code:
#returns true if number is prime else false
def is_prime(num):
    tempnum = 0;
    if num == 2:
        return True;
    if num < 2:
        return False;
    for x in range(3,num,2):
        tempnum = num % x;
        if tempnum == 0:
            return False;
    return True;

#sum starts with the value of 2 because 2 is a prime number    
sum = 2;

#skip al even numbers because non are prime except 2
for num in range(1, 5001, 2):
    #add number to sum if the number is prime
    if is_prime(num):
        sum = sum + num;
print('Prime sum: ' + str(sum));

note for the isprime function all you need to do is go up to the square root of a number for the loop. I will save time for large numbers. I did not include it in this source because I didn't really need it
Visit this user's website Find all posts by this user
Quote this message in a reply
12-04-2009, 11:17 PM
Post: #2
RE: Prime sum challenge
Very good solution i must say.
I made that in Pascal too :
Code:
program sum_of_primes_below_5000;
uses wincrt;
var
i,s:longint;
function prime(k:longint):boolean;
var
  i,g:longint;
  b:boolean;
begin
  if k mod 2 = 0 then
  if k=2 then
  prime:=true
  else
  prime:=false
  else
  begin
  if k=3 then
  prime:=true
  else
  begin
  b:=false;
  g:=round(sqrt(k));
  i:=3;
  repeat
    begin
      if k mod i = 0 then
      b:=true;
      i:=i+2;
    end;
  until (i>g) or (b=true);
  if b=true then
    prime:=false
  else
    prime:=true;
  end;

end;
end;
begin
s:=0;
for i:=2 to 5000 do
  if prime(i) then
    s:=s+i;
  writeln(s);
end.
I have the same result as you have !

There's a fine line between genius and insanity. I have erased this line.
Oscar Levant
There's a fine line between an administrator and black hat hacker. I have erased this line.
Dr DEBCOL
Visit this user's website Find all posts by this user
Quote this message in a reply
12-05-2009, 12:42 AM
Post: #3
RE: Prime sum challenge
awesome code Smile
Visit this user's website Find all posts by this user
Quote this message in a reply
Post Reply 


Forum Jump:


 Quick Theme: