/log

life.log()

Using yield while generating the sum of first 1000 prime numbers

with 2 comments

I like using yield here and I was happy when I knew that scala has yield

def oddNumbers(xlist):
	for item in xlist:
		item += 2
		xlist.append(item)
		yield item

oddNumbers 		= oddNumbers([7])
primeNumbers	= [2, 3, 5, 7]
count			= 3
summation		= 17

for item in oddNumbers:
	isPrime = True
	for otherItem in primeNumbers:
		if item % otherItem == 0 and item != otherItem:
			isPrime = False
	if isPrime:
		primeNumbers.append(item)
		count += 1
		summation += item
	if count == 999:
		break

print summation

Written by me

September 10th, 2011 at 11:20 pm

2 Responses to 'Using yield while generating the sum of first 1000 prime numbers'

Subscribe to comments with RSS or TrackBack to 'Using yield while generating the sum of first 1000 prime numbers'.

  1. would you please explain what you are trying to achieve here?

    Ahmed Soliman

    13 Sep 11 at 6:35 PM

  2. Goal is to calculate the sum of the first 1000 prime numbers:

    Prime numbers are odd numbers
    For any prime number it shouldn’t be divisible by any of the previous prime numbers.

    Technically:
    >The first function is generating the next odd number exactly like xrange except that xrange has upper limit and this one doesn’t.

    >I used 2,3,5 and 7 to initialize the primesList
    >I initialized oddNumbers iterator with [7] and I used it in the for loop, so it’s going to generate 9, 11, 13, ..
    >Another loop, the inner loop is doing the following
    >>it’s looping on the primeNums list length.
    >>it’s checking if the current number isn’t divisible by all numbers then it:
    >>> counts it (as we only need 1000 primes)
    >>> add it to the summation
    >>> add it to the primeNums list so next time it should be included in the checking process.
    >>else it will change the isPrime flag to false and will skip it to the next odd number

    Note: I know count =3,sum= 17, if count=999 are all magic numbers and they should be commented to let you know what I’m doing
    >>3 is the start index 2->0, 3->1, 5->2, 7->3
    >>17 is the summation or 2,3,5,7
    >>999 is the limit

    clear enough ?

    me

    13 Sep 11 at 10:35 PM

Leave a Reply

Get Adobe Flash playerPlugin by wpburn.com wordpress themes