elz: (ada-tubes)
elz ([personal profile] elz) wrote in [community profile] intro_to_cs2009-11-11 10:52 pm
Entry tags:

Poll & solutions

First:

Open to: Registered Users, detailed results viewable to: All, participants: 25


Tickyboxes!

View Answers

Finished lecture 2
24 (96.0%)

Finished problem set 1
15 (60.0%)



Also, it occurs to me that it might be handy to have a place to post/discuss solutions to the problem sets, to see what we can learn from each other in the absence of TAs. If you actually go to MIT and the problem sets are still the same, don't read these. ;)

Fire away!
yhlee: Alto clef and whole note (middle C). (Default)

[personal profile] yhlee 2009-11-12 08:17 pm (UTC)(link)
I first defined a helper function to check primarily (starts from scratch each time but only goes up to the square root)

# So we can use sqrt and log
from math import *

# helper function: is the given number (positive integer) prime?
def is_prime(number):
	i = 2
	sqrt_n = math.sqrt(number)
	while i <= sqrt_n:
		if number%i == 0:
			return 0
		else:
			i = i + 1
	return 1


Then for Problem 1:
def thousandth_prime():
	# first candidate prime after 2
	number = 3
	
	# we start counting with the 2nd prime, as the first is 2
	counter = 2

	while counter <= 1000:
		last_prime = 2
		if is_prime(number) == 1:
			print "Prime no.", counter, "is", number
			last_prime = number
			counter = counter + 1
		number = number + 2
	print "The thousandth prime is", last_prime
luckykitty: Cartoon avatar created on madmen site (Default)

[personal profile] luckykitty 2009-11-14 09:03 pm (UTC)(link)
Thank you for sharing your solution... My solution to problem 1 was really similar to yours! Except I didn't define it as a function, so had to include a flag for whether or not it was a prime and then test that afterwards. I really like having the function, as it makes it so much easier to read. Cool! *learns*

Could you also return True or False rather than 1 or 0, and then just test if is_prime is true? I guess it's six of one?
yhlee: Alto clef and whole note (middle C). (Default)

[personal profile] yhlee 2009-11-14 09:16 pm (UTC)(link)
Yes, I believe you could return True or False (boolean) instead of 1 or 0. I think my brain is stuck in some other programming language I learned earlier where booleans return as 1 or 0 so I reverted. Whoops. :-D

I am a great believer in helper functions--they let me break down the problem into chunks. ^_^