Friday, 15 June 2012

Problem 10 Project euler

here is my solution, takes 113 seconds on my computer.
# Returns a list of primes less than 'n'.

import is_prime

def leq_primes(n):
 import time
 start=time.clock()
 li=[2]
 for i in range(3,n,2):
  if is_prime.is_prime(i)==True:
   li.append(i)
 
 sum=0
 for e in li:
  sum=sum+e
 run_time = time.clock() - start 
 return sum,run_time 

if __name__ == "__main__":
 n = raw_input("Input: ")
 n = int(n) 
 print leq_primes(n)




and here is the code for is_prime.py file,

# Returns true if a number is prime,returns false other wise.

def is_prime(n):
 d=True             
 r=int(n**.5)+1           # sets r as root(n) +1
 for i in range(2,r,1):   # looking just at ood numbers, as all primes are odd, except 2
  if n%i == 0:
   d=False
 return d
 
if __name__ == "__main__":
 n = raw_input("Input: ")
 n = int(n) 
 print is_prime(n)








Post a Comment