Sunday, August 3, 2014

Pernicious Bugs

Summary: Following snippet took more than 10 hours to execute, which could be improved at amazing level by shifting just one line :)

Program is to find the sum of all prime number less than 2 million

# function to check if number is prime


def is_prime(num):
# prime numbers are greater than 1
   # check for factors
   for i in range(2,num/2 + 1):
       if (num % i) == 0:
           #print(num,"is not a prime number")
           return False
   else:
       #print(num,"is a prime number")
        return True

sum = 0
for i in range(2, 2000000):
    n = 0
    if is_prime(i):
        n = i
    sum = sum + n

print sum


IMPROVEMENT:
for i in range(2, 2000000):
    n = 0
    if is_prime(i):
        n = i
        sum = sum + n

print sum


REASON: Above shift of line inside if condition avoided the execution of statement "sum = sum +n" for all the numbers that were not prime too, which was of course undesirable.









No comments:

Post a Comment