A community for students.
Here's the question you clicked on:
 1 viewing
vegeta
 4 years ago
if I can't even understand how to do the first problem should I stop trying to learn how to program?
vegeta
 4 years ago
if I can't even understand how to do the first problem should I stop trying to learn how to program?

This Question is Closed

vegeta
 4 years ago
Best ResponseYou've already chosen the best response.0and if I were to go to college for it would the teachers have to help me until I understood it?

somnamniac
 4 years ago
Best ResponseYou've already chosen the best response.10It's definitely confusing in the beginning, but you can get through it. What are you having trouble with?

Captain119
 4 years ago
Best ResponseYou've already chosen the best response.2Vegeta i been trying with this prime problem for 2 hours with out no luck 5 mins talking to Somna and him pointing out a few things i got it working so as long as you have the right resources everything can be accomplished if you put your mind into it programming is like everything else you have to work to learn nothing is easy

Owlfred
 4 years ago
Best ResponseYou've already chosen the best response.2Don't give up! OpenStudy can be your teacher :)

vegeta
 4 years ago
Best ResponseYou've already chosen the best response.0well when I look at examples of the program to find the 1000 prime number I can sorta understand it...but then when I try to write it myself without looking at those I just get completely lost and I don't really want to have to look at other people's programs while I try writing my own, I feel like I'm just cheating that way.

Captain119
 4 years ago
Best ResponseYou've already chosen the best response.2bread it down into peices think of the steps you will have to take and do it step by step thats what helped me do it i mean ofcourse i ended up with more line of code than probably needed but once you understand the logic behind it as time goes you will be better at it

vegeta
 4 years ago
Best ResponseYou've already chosen the best response.0well, I'll keep trying..it's really frustrating not being able to comprehend it, thanks for your guys' input :)

somnamniac
 4 years ago
Best ResponseYou've already chosen the best response.10One really good way to look at problems (at least, the one that I always use) is to try to describe the problem in regular language, step by step, in a way that I think I could write in program form. So for the prime numbers one, the first thing I want to do is talk through how I would do it with pencil and paper: Start with a number see if it's prime if it is, add one to the number of primes I've found move to the next number Then I try to expand the steps, starting with the one that seems most confusing. In this case, it's definitely: How am I going to see if it's prime? So I try to answer that: Take an integer # Note to self, I need an integer here, better create a variable for one Try to divide it by every number less than it # NtS going to need another integer. I need to think about the initial value, because I'm using it as a divisor If it divides evenly, go to the next number # What test can I use to see if it divides evenly? etc... Ask for help when you need it. And when you see solutions that work, a good strategy is to go line by line making sure you know what each operation does and how the variables are changingI tend to actually comment out every line even on simple programs when I'm trying to learn how to think about them.

somnamniac
 4 years ago
Best ResponseYou've already chosen the best response.10Oh, there's one other thing that's important to notice if you're getting diiscouraged: Make sure you're actually doing the correct assignment for the lecture you're onfor instance, Assignment 1 is 'due' in Lecture 3. The Calendar page on the MIT coursepage has those dates.

Captain119
 4 years ago
Best ResponseYou've already chosen the best response.2now that makes sense LOL i was still watching lecture 2 and i'm like there is nothing about this in both of the first lectures

vegeta
 4 years ago
Best ResponseYou've already chosen the best response.0well, I'll try writing it out on paper first, hopefully that helps me understand where all the variables are coming from like you said...thanks.

somnamniac
 4 years ago
Best ResponseYou've already chosen the best response.10The other reason it's good to do that is that it's easier to ask for help if you've written it out. You can say, "Here, this is how I'm trying to approach the problem but I'm having trouble with this step" That makes it easier for people to see where you are and ask the right questions.

Radly
 4 years ago
Best ResponseYou've already chosen the best response.20vegeta: I was told by my Freshman roommate I should give up the idea of engineering because (basically) I didn't know as much as he did. I flunked out of my first university. I eventually got my Ph.D. in EE. My first two programming classes in college (Fortran II and Algol 60) I never got a single program to work. I've been a software engineer for over 30 years now. Quitting just because it's hard to get started is not a recipe for success. Hang in there. There's a bunch of people here who are ready, willing, and able to help you get over the hump.

abby
 4 years ago
Best ResponseYou've already chosen the best response.0Thanks for the encouragement, Radly! Vegeta: I gave up on that primes problem, and I'm having much more success now. Do follow the calendar. And accidentally making an empty post is no indication of my computer skills, honestly. ;)

vegeta
 4 years ago
Best ResponseYou've already chosen the best response.0y = 1 divider = 2.0 num = raw_input("what number do you want to know about?") num = int(num) import math z = math.sqrt(num) if num/num == y and num/y == num and (z*z)%divider < y : print 'prime' else: print 'not prime' what am I doing wrong? I'm just trying to make something to tell me whether a number is prime or not right now.

somnamniac
 4 years ago
Best ResponseYou've already chosen the best response.10Hi! Let's look at what this is doing.

somnamniac
 4 years ago
Best ResponseYou've already chosen the best response.10y = 1 Assign the variable y to the integer 1 divider = 2.0 Assign the variable divider to the floatingpoint number 2.0 num = raw_input("what number do you want to know about?") assign the variable num to the user's input after the prompt "what number do you want to know about?" num = int(num) make the type of num an integer import math Load the functions in the math module z = math.sqrt(num) assign the variable z to the square root of num (the number the user input after the prompt, so if they said 25, z is 5) if num/num == y and num/y == num and (z*z)%divider < y : if the number divided by itself is 1, and the number divided by 1 is the number, and the square root of the number times itself divided by 2.0 is less than 1 print 'prime' print 'prime' else: print 'not prime' Otherwise print 'not prime

vegeta
 4 years ago
Best ResponseYou've already chosen the best response.0I guess "(z*z)%divider < y " doesn't do much for it to tell if it's prime or not..just don't know what to put there to figure it out..

somnamniac
 4 years ago
Best ResponseYou've already chosen the best response.10well, they suggest that you use exhaustive search, which means checking every possible answer. In this case, that means if you're checking 5, you want to try to divide by 2, then 3, then 4 and see if any of those work. I don't know if there's a single formula to determine primeness, but I know that's not the way this specific problem is presented. Can you think of a way to try to divide a number by every number between 1 and itself?

vegeta
 4 years ago
Best ResponseYou've already chosen the best response.0would I have to do a "while" test ?

somnamniac
 4 years ago
Best ResponseYou've already chosen the best response.10that might work, but a 'for' loop would give you the range automatically. try running this: num = int(raw_input("what number do you want to know about?")) for x in range(1,num): print 'num ',num print 'x ',x print 'num divided by x ',num/x

somnamniac
 4 years ago
Best ResponseYou've already chosen the best response.10that will try to divide the number you enter by every number between 1 and itself, and at each stage print the variable values and the result

vegeta
 4 years ago
Best ResponseYou've already chosen the best response.0where'd you get the for in and range words from? I didn't see 'em in lecture 2...were they in the 3rd one?

somnamniac
 4 years ago
Best ResponseYou've already chosen the best response.10that's a good question. I'll check.

somnamniac
 4 years ago
Best ResponseYou've already chosen the best response.10I haven't watched lecture 2 in a while, but there's a for loop on the lecture 2 handout

vegeta
 4 years ago
Best ResponseYou've already chosen the best response.0I found it, wish I would've looked at that before I even came on here asking questions...I have a feeling it's gonna help a lot, thanks for pointing that out :)

somnamniac
 4 years ago
Best ResponseYou've already chosen the best response.10So we know how to try to divide a number by all the numbers we need to try. But that's actually too much information. What we need to do is try all of those numbers, but just give us one piece of information: we only need to know if there were any numbers we tried that divided evenly. We're looking for either True (There are NO numbers that divide evenly, so it is prime) or False (there ARE numbers that divide evenly, so it isn't prime)

somnamniac
 4 years ago
Best ResponseYou've already chosen the best response.10That probably means an 'if' test. So can you think of a test of whether something divides evenly by something else?

vegeta
 4 years ago
Best ResponseYou've already chosen the best response.0if x/2.0 < 1 : print 'odd' else: print 'even' ???gahh my brain just feels like it's all tied up

vegeta
 4 years ago
Best ResponseYou've already chosen the best response.0I'll bbiab ...I need to get away from this for a while I feel like I'm gonna throw my keyboard thru the monitor, thanks for all your help so far !

somnamniac
 4 years ago
Best ResponseYou've already chosen the best response.10Cool. Walking away for a bit usually helps me think more clearly when I get stuck too.

Radly
 4 years ago
Best ResponseYou've already chosen the best response.20I know how he feels. When he gets to the lecture on debugging and finds out an MIT professor recommends "just walk away" he'll feel a whole lot better. :)

shadowfiend
 4 years ago
Best ResponseYou've already chosen the best response.1I'll give you a secret while you're at it, though: in Python, and most languages, you can use % instead of / to determine the remainder of a division (the modulus, as it's called). So for example 5 % 3 is 2 because 3 goes into 5 once with a remainder of 2.

vegeta
 4 years ago
Best ResponseYou've already chosen the best response.0I'm still lost.. is the x every number up to the 'num' ? and I feel like I'm just making this harder than it should be..I don't see anyone else having this much trouble >.<

somnamniac
 4 years ago
Best ResponseYou've already chosen the best response.10The statement for x in range (0,20) means 'do the next stuff for x = 0, then do the next stuff for x = 1, etc, up to x = 19.' The for loop stops one integer before the last integer in the range.

somnamniac
 4 years ago
Best ResponseYou've already chosen the best response.10but let's leave that aside. Shadow offered a good solution to the other problemthat the % operator gives the remainder of division. What's the remainder of, say, 20/5?

somnamniac
 4 years ago
Best ResponseYou've already chosen the best response.10right. 5 divides evenly into 20, so the remainder is zero. We know that if the remainder of an integer division problem (x%y) is zero, x must be evenly divisible by y.

vegeta
 4 years ago
Best ResponseYou've already chosen the best response.0so if I do a prime%2 it has to be more than 0 so that'll define whether it's prime or not?

somnamniac
 4 years ago
Best ResponseYou've already chosen the best response.10how about this: We take the number we're testing We try to divide it by EVERY number between 1 and the number we're testing. if the number we're testing is evenly divisible by ANY number: it isn't prime.

vegeta
 4 years ago
Best ResponseYou've already chosen the best response.0I just don't get it...how do I tell it to check the numbers that the for code printed out

somnamniac
 4 years ago
Best ResponseYou've already chosen the best response.10numToTest = int(raw_input("what number do you want to know about?")) #get a number to test for primeness isPrime = True #Assume it's prime until we prove otherwise for x in range (2,numToTest): ##we're going to try all the numbers 2(numToTest1) inclusive if numToTest%x ==0: ##if the remainder of numToTest/x is zero isPrime = False ## set the value of isPrime to False if isPrime == True: print 'the number is prime' else: print 'the number is not prime'

Radly
 4 years ago
Best ResponseYou've already chosen the best response.20(Tell me if having one more coach just confuses the issue and I'll go back to lurking.) vegeta, "x % 2" tells whether x is even or odd, not whether it's prime. That is, if x % 2 is 0, x is divisible by 2. If it's not 0, it's not divisible by 2, and you need to test x % 3. If that remainder is not 0, x is not divisible by 3. In that case, you test x % 4. And so on, until you get to x  1. Once you understand that concept, you're well on your way. Then we can talk about how to reduce the number of tests.

vegeta
 4 years ago
Best ResponseYou've already chosen the best response.0thank you somnamniac , that makes a lot more sense. I'll have to take note that true and false are python words, I think I'll have to work that problem thru my brain a few times for it to finally sink it but I think I'm on the right track, I appreciate you helping to teach me this stuff. and radly any help I get is appreciated ..I get that if x%2 = 0 then it's even and stuff, just having trouble figuring out how to plug everything in and link it all together into the final program.

somnamniac
 4 years ago
Best ResponseYou've already chosen the best response.10the important stuff happens in these two operations: if numToTest%x ==0: ##if the remainder of numToTest/x is zero isPrime = False ## set the value of isPrime to False if isPrime == True: print 'the number is prime' the first if statement sets the isPrime variable to False if ANY number divides evenly into it so for the number 12, that statement will set isPrime to False at two, and then again when it gets to 3, and then again when it gets to 4, and then again when it gets to 6. We don't care how many times isPrime gets set to False; all we care about is that if it EVER gets set to False, it stays False. That's why we don't include any statement that could set isPrime back to True. The next if statement happens after we've tested every number (you can tell because it's not indented at all). It just looks at isPrime. isPrime started out as True, so if nothing happened to change it to False along the way, it should still be True. If it's True, the number is prime. If it's False, the number must have been evenly divisible by one of the numbers we tried.

Radly
 4 years ago
Best ResponseYou've already chosen the best response.20Do you follow somnamniac's last post? If you run it, does it produce the correct answer for you?

vegeta
 4 years ago
Best ResponseYou've already chosen the best response.0yeah I follow it and it's right..so for the number 12 it's going to divide 2 and 'say' it's false...and it's going to keep going , why wouldn't it just stop at 1 false and call it not a prime

Radly
 4 years ago
Best ResponseYou've already chosen the best response.20That's where we get to the part about how to reduce the number of steps.

Radly
 4 years ago
Best ResponseYou've already chosen the best response.20Grrrr, forgot my new rule about saving my posts... Vegeta, you can stop a for loop at any time with a "break" statement. In this case, add a line right below the "isPrime = False" line that just says "break".

vegeta
 4 years ago
Best ResponseYou've already chosen the best response.0typing break would just speed up the computation of a large number right?

Radly
 4 years ago
Best ResponseYou've already chosen the best response.20Yes. And there are other improvements. This one just stops when you know it's not prime.

Radly
 4 years ago
Best ResponseYou've already chosen the best response.20Let me correct that last response. No, it doesn't speed up the computation for a large number. It only stops the computation when the number is known not to be prime.

somnamniac
 4 years ago
Best ResponseYou've already chosen the best response.10I suspect Radly will be better than me at explaining how to optimize this, but I want to say one last thing. The answer to the question "Why wouldn't it stop after it set isPrime to False?" is "We didn't tell it to stop after that." Most of the problems I have when writing programs come from the fact that I assume the computer 'knows' what I want. In this problem, all the computer knows is that there are three variables (numToTest, x, and isPrime) and those three variables are associated with values. The computer does NOT know what a prime number is, or that we're looking for them, or that the variable isPrime refers, to us, to whether or not numToTest is prime. It's important to remember that the computer does (and knows) only and exactly what you tell it.

vegeta
 4 years ago
Best ResponseYou've already chosen the best response.0that makes sense, if a computer knew what a prime number was we wouldn't have to make a program for it :p

Radly
 4 years ago
Best ResponseYou've already chosen the best response.20That's the idea. A long time ago asked a language designer to give me a language with the "DWIM" instruction. "Do What I Mean". :)) And no, you'll probably never have to write a prime number program in a real job. It just turns out to be a bitesized problem that's big enough to get you started in realizing all the details you have to think about in programming.

vegeta
 4 years ago
Best ResponseYou've already chosen the best response.0that's what I'm worried about..if this problem is giving me this much trouble what's a program for a real job gonna do to me :p

Radly
 4 years ago
Best ResponseYou've already chosen the best response.20By the time you get a real job programming, believe me, this part of programming will be second nature to you. It's so much like learning a foreign language that in the early days some universities gave you credit hours for foreign language if you passed a programming class.

shadowfiend
 4 years ago
Best ResponseYou've already chosen the best response.1You have to walk before you can run :) Put differently, thinking about stopping now because this problem is hard is like deciding not to try walking when you're 2 because Usain Bolt runs 100 meters in 9.69 seconds. You know you're learning when what you're trying to do feels hard :)

vegeta
 4 years ago
Best ResponseYou've already chosen the best response.0do you guys think if I look at one of the finished programs and type it out over and over again that it'd help me remember the stuff better and in the end I'd be able to do it on my own without just copying? I have a really bad memory and I can look at the program then try to go and write my own and I'll forget anything from that program I was just looking at ><

somnamniac
 4 years ago
Best ResponseYou've already chosen the best response.10I think if you 'translate' every line of the code from Python into English by yourself you'll have a better idea of what it does.

somnamniac
 4 years ago
Best ResponseYou've already chosen the best response.10But when you translate, be careful to only use what the computer would know. So the line if isPrime == True: does NOT translate as 'see if the number is prime' it DOES translate as 'see if the variable isPrime points to the value True' like I said, the computer has no idea what a prime number is.

Radly
 4 years ago
Best ResponseYou've already chosen the best response.20Interesting idea, there. I do a lot of learning by typing in programs from tutorials and textbooks. But you should think about every line you type. What variables are in it? What conditions are being tested? Why is it there? And one of the side benefits is that if you're like other mortals, you'll occasionally mistype something and then you have to figure out why it's not working as expected. That's where the real learning comes in. And you can incorporate somnamniac's suggesting by sprinkling explanatory comments in your code. Python has a good documentation feature (triple quote marks). Add such documentation to every function you type in. And if they're already there in the sample you're copying, expand them with your own thoughts.

vegeta
 4 years ago
Best ResponseYou've already chosen the best response.0well thanks to everyone for helping me today, I really do appreciate it, I'll see what I can get done over the weekend and let ya'll know how it goes, have a good weekend everyone!

Radly
 4 years ago
Best ResponseYou've already chosen the best response.20I'm looking forward to hearing that first "Eureka!". Enjoy your weekend.

Aslander
 4 years ago
Best ResponseYou've already chosen the best response.0@vegeta  You are not alone! I just started this course, and my first attempts took me longer than I could ever imagine. After at least 30+hours, I finally got my code to work...but I did learn so much from that trial and error period. If you need a deeper understanding of the primes, read this: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes. It was a tremendous help to me for the primes problems set.

Aslander
 4 years ago
Best ResponseYou've already chosen the best response.0ps. This page will give you the answer  but I suggest NOT reading that part! ;)

onel3d
 4 years ago
Best ResponseYou've already chosen the best response.0the best problem solver that I have found when programming is to read the documentation and find examples there. if you are not used to the language and it's way to problem solve it can be hard to get around. I actually started reading this post to find the same answer but the and to the problem is in the same python documentation, you just need to edit their script to loop throught the results and find number 1000. I am still working on this loop but I know I can get it to answer me in primes. Thanks for all the help you guys posted here

light
 4 years ago
Best ResponseYou've already chosen the best response.0# let n be the number of primes found so each prime found adds 1 to the value of n #Also let n start at 1 as the number 2 wont be counted by program n = 1 #To check if a number is prime divide it by each number if the remainder is zero #then it is not prime and the next number can be checked #Note: % gives the reaminder so if a%b = 0 then number is not prime #Let t be the number to be tested to show if its prime #Start with 3 and take 2 to be first prime as above t = 3 #Let d be the number to be divided into t d = 2 #limits the process to the nth term, in this case 999 (as 1 is the start value for n #as stated earlier while(n<1000): #tells the process to stop when d<t stopping it from usind divisors more than t (could be #more efficient with t divided by 2 + 1) while (d<t): if t%d == 0: #if this works number isnt prime move onto next value of t to be tested and reset d to 2 t = t+1 d = 2 #test the next value of d else: d = d + 1 #once all values of d are ruled out as d<t this loop is broken. The process then gives a #value for t which at this time must be prime. It then adds 1 to the number of primes found #in the prime counter (n) and takes the next value of t to continue, reseting d again print t n = n+1 t = t+1 d = 2 #the while clause at the start finaly ends the process when 1000 primes are found Thats how i did it, i think it worked quite nicely with just simple terms, i know it could be made more efficient but it works out well Dont copy and paste though thats not how you learn :)

Aslander
 4 years ago
Best ResponseYou've already chosen the best response.0Don't forget that you don't need to use such a high range for the divisor. You can stop considerably earlier. Nice job.

light
 4 years ago
Best ResponseYou've already chosen the best response.0i know but i didnt want anything but just the simplest mathmatically, the original way i planned it was kinda crazy (it involved dividing each number to be tested by each previous found prime which is technically the shortest way to do it) But for simplicity's sake i just used simple obvious math to avoid confusion :)

mo
 4 years ago
Best ResponseYou've already chosen the best response.0Just joined no experience before so this exercise is doing my head in. Here is what I have and it just loops. Any help would be greatly appreciated. n=int (1) ##This will act as counter s=int (3) ## A number to get us started divs=int (2) ## Integers I will diving with. while n<5: ## to ensure I kill at 1000th prime while s%2 != 0: ## If its an even number it isnt prime while divs<s: ## make sure devisors remain below value while s%divs==0: ## test to see if prime divs= divs +1 ## add one to divisor else: n = n +1 else: n= n+1 else: s = s+1 else: print s

tyoungjr
 3 years ago
Best ResponseYou've already chosen the best response.0yes the first problem was pretty difficult for me too but I'm glad to say I completed it , and the second problem. What helped me the most were the hints given in the description. And having a set of data to test against , breaking down each step was key as well. Feel free to message me if you still need help.

mtoyama
 3 years ago
Best ResponseYou've already chosen the best response.0Mo, I'd be super careful with multiple nested loops (my own rule) because things start to get really complicated and wacky when you do that. Rules I used to simplify my prime program: 1. We know the (strict) definition of a prime: a number divisible only by itself and unity. Thus, you can rule out a large set of numbers  even numbers greater than 2. We will only test odd numbers. 2. Use your dynamic list of primes also as a list of divisors. Why? Because a) even divisors are not applicable to the problem, see #1, b) any nonprime odd numbers are simply multiples of primes. Make use of the for loop and add to your list of primes when you find one. Ensure you're not adding to your list of primes within your for loop or without breaking the loop or you'll create an infinite loop. There are other ways to do this. I originally could not get the for loop to work so I made an overly complex doublenested while loop which essentially did the exact same thing as a for loop, except in a longwinded manner.

benevolence22
 3 years ago
Best ResponseYou've already chosen the best response.0Forgive me for playing devil's advocate, but I spent many long hours on problem 1 in search of finding a way to define prime numbers, and some of the explanations listed above did not work (at least for me, for some reason). Please help me spot my error, and then I'll demonstrate a simpler solution I developed. When I employed the following: dividend = 3 prime = [2,] #creates list of primes, 2 already included while len(prime<=999): #lists start counting at zero for i in range (2,dividend): if dividend%i==o: #number is not prime dividend+=1 #move to next step else: prime +=[dividend,] #add dividend to list prime dividend += 1 print prime By doing this, I only generated a list of odd numbers, not a list of prime numbers. For this reason, I don't believe that dividend%i==0 is a good test for finding a prime number. I believe my error was that once the computer ran a test for dividend%i==0 and found it false for any i, it immediately resorted to the "else" column and added the dividend to my list of primes. Therefore, a number like 15 (not prime) would be added to my list of primes because 15%2!=0. For those who had success using dividend%i==0 as a prime test, how did you avoid this? What I ended up using instead (much simpler) was a mathematician's definition of prime, specifically the Fermat primality test: if ((2**dividend)2)%dividend==0: prime += [dividend,] #number is prime This prime check worked, which meant I only needed to control the flow until my prime list was created. I was able to generate the prime list, and my code is very short and simple. SO MUCH EASIER! Is this cheating? I didn't eliminate positive numbers as an initial step (as suggested on the assignment), but why should I have to if Fermat's test will do so for me automatically? Anyways, eliminating positive numbers could easily have been included, simply by testing for dividend%i==0 :) As computer scientists, I don't think we should bang our heads on the wall devising new methods for defining prime numbers when mathematicians have already done the work for us? I consider this no different than importing a module, I suppose. But that's just my take on it. So... what am I missing?

Alfram
 3 years ago
Best ResponseYou've already chosen the best response.0Yea, benevolance i know what you are missing. First problem is that your for loop doesn't end, when divisor%i==0 is true, though it still adds +1 to the divisor. Therefore i doesn't reset, whenever divisor%i==0 is true. I had this problem too. You should add a break statement to terminate the for loop when divisor%i==0 is true. by terminating the for loop you return to the while loop which the reinitializes the the for loop with i starting at 2. The other mistake is that your else statement is in line with the if statement. basically what your program is saying; is that if a number doesn't divide evenly with a single [i] its added to the list of primes. What you want is to add it to the list of primes, when there is no [i] that divides evenly for all [i]s. So the else statement should be moved in line with the for loop. correcting typos the o to 0 and len(prime<=9999 to len(prime)<=1000. then you program should end up looking like this: dividend = 3 prime = [2,] #creates list of primes, 2 already included while len(prime)<=999: #lists start counting at zero for i in range (2,dividend): if dividend%i==0: #number is not prime dividend+=1 #move to next step break else: prime +=[dividend,] #add dividend to list prime dividend += 1 print prime Which prints a list of the 1000 first prime numbers. My own code is similar though i only divide possible primes with the primes that i have already found, which is fewer steps. Also i avoid the even numbers by adding 2 to the dividend every time. my own code is this: print 'Which prime do you want?' #asks the user which Prime number to calculate response = raw_input() target = int(response) PRIMES = [2, 3] X = PRIMES[1] + 2 #X is the Next candidate for beeing a Prime. while len(PRIMES) < target: for i in range(len(PRIMES)): if X % PRIMES[i] == 0: X = X + 2 break else: PRIMES = PRIMES + [X] print 'The ' + response + '. prime number is ' + str(PRIMES[1]) + '.'

cghd
 3 years ago
Best ResponseYou've already chosen the best response.0alfram  great short simple code. thanks for sharing  I couldn't figure out how to get the program to step through the existing primes, so it is useful to see your use of for/in. my code example below takes more work (and could be reduced much more). the only thing is does, in addition to testing candidates by previous primes, is stop testing after the primes get larger than 1/2 the candidate. This saves computation once the list gets long. primes = [2] # start with the first one you know count = len(primes) #how many numbers are in my list can = 3 #candidate number (later, I add 2 at a time, to produce only odds) round = 0 #this tell how many times the candidate has been tested div = primes[round] #the program tests each candidate by all previous primes in the set #that are less than 1/2 the candidate remain = can%div #how many are in the remainder when a candidate is divided hi = max(primes) #this keeps track of and updates what the highest prime nthprime = raw_input('what randomith prime number do you want to see now? ') nthprime = int(nthprime) while count < nthprime: if div > (can/2): primes.append(can) #add can to the list count = len(primes) #update count round = 0 #reset round & divisor div = primes[round] #update div remain = can%div #reset remain can += 2 #try the next number hi = max(primes) #update hi elif remain > 0: round += 1 #try the next number in primes div = primes[round] #update remain = can%div #reset remain elif remain == 0: round = 0 #reset round div = primes[round] #reset div remain = can%div #reset remain can += 2 #try the next number print 'here it is!' print max(primes)

sachin91
 3 years ago
Best ResponseYou've already chosen the best response.0I'm programming for the first time too and this took me a couple of hours  spent mostly staring at the screen. Its only when I wrote down my thinking on paper that I got somewhere. Its a satisfying feeling getting it right, although i realize this is supposed to be easy and is early days on the long road to being a decent programmer!

shadowfiend
 3 years ago
Best ResponseYou've already chosen the best response.1Loving programming is all about that feeling of getting it right, every day :) And this isn't easy, it's basic. There's a difference. Basic is hard at the beginning.

boids
 3 years ago
Best ResponseYou've already chosen the best response.0When I read "I'm programming for the first time too and this took me a couple of hours  spent mostly staring at the screen." I became enlightened.

tdsamardzhiev
 3 years ago
Best ResponseYou've already chosen the best response.0@MPizzie, your program does nothing, because in your "for loop", the first thing you do is trying to divide the number by 1 :) Then you break out of the for cycle, and try dividing the next bigger number by 1. That is called an endless loop, because "count" is never increased, and every number, even the primes, are dividable by 1. Another error is skipping 2, which is also a prime number. Third error is the endrange of your for loop, as you divide the number by itself, which would always return true (as with 1). My answer is kind of late, but I still hope it would be of help! Best regards, Todor

tony1404
 3 years ago
Best ResponseYou've already chosen the best response.0I am having the same trouble understanding the structure of the comparisons.

AlwaysJovial
 2 years ago
Best ResponseYou've already chosen the best response.0Thank you, thank you, thank you Alfram not sure if you'll see this but but Ive been working on this problem for sometime and it wasnt until you put up the part cautioning the use of the else clause and how to use it properly. for those that are still interested here is how I did it: import math primeNumth = float(raw_input('which prime number? ')) ##get user input primeSqrt = int(math.sqrt(primeNumth)) ##define squareroot for max range primesAre = [2, 3] ##create a list of primes starting with 2 & 3 primeCandid = primesAre[1] + 2 ##set the iteration for prime candidate ##set while loop ##while len(object) is less than user input or sqrt of user input ##used to shorten calculation time while len(primesAre) < primeNumth or len(primesAre) < primeSqrt: for i in range(len(primesAre)): ##loop for each i in range of list if primeCandid % primesAre[i] == 0: ##start test primeCandid = primeCandid + 2 ##if not prime add 2 break ##break from current for and start at ##while with new primeCandid else: primesAre = primesAre + [primeCandid] ## add primeCandid to list print 'the ' + str(int(primeNumth)) + 'th prime is: ' + str(primesAre[1]) ##prints last object in primesAre list ##many thanks to Alfram

Alfram
 2 years ago
Best ResponseYou've already chosen the best response.0@AlwaysJovial You'r welcome, always glad to help. :)

Spitfire96
 2 years ago
Best ResponseYou've already chosen the best response.0I know this is a little late since the last post was made 2 months ago but i tried to make a faster version of the program that just loops through everything checks if its a prime or not by dividing it by all the possible numbers and i made it for a range of numbers so say numbers 1 to 1000... and it works, for any number under 120 anyway . the only thing is i'd like it to work for every number. if anyone can think of a solution it would be greatly appreciated. here is the code: #Find out which numbers are prime and which ones are not prime in a set of #numbers set by the user. print 'User, this program is used to find out which numbers in the sequence you' print 'will choose are prime and which are not prime.' print ' ' print ' ' start = int( raw_input( 'User, please enter the value you wish to start at as an iteger: ' )) stop = int( raw_input( 'now enter the value at which you wish to stop ( this value will be included in the calculations ) : ' )) def testPrime( num ) : loopSequence = '' for value in range( 2, 10 ) : if value == num : pass else: strValue = str(value) loopSequence += strValue for divisor in loopSequence : divisor = int(divisor) num = int(num) testInt = float( num / divisor ) testFloat = float(num) / float(divisor) compare = testInt == testFloat if compare == True : break if compare == False : return 'prime' elif compare == True : return 'nonprime' for num in range( start, (stop+1)): test = testPrime(num) #print num, ' is a '+test+'number.' #this is to know if all numbers in sequence if test == 'prime': print num, ' is a '+test+' number.' #this is to know only the prime numbers this site is the way i test if the program is right: http://primes.utm.edu/lists/small/1000.txt I am relatively new to programming but I seem to have a knack for it and i love it too. So if I'm doing something wrong just explain it quickly and I'll see what i can do.

shadowfiend
 2 years ago
Best ResponseYou've already chosen the best response.1You're doing some pretty cool stuff there, but there's one big thing that can help you I think: %. The % operator is called “mod”, and it gives you the remainder of a division. It's much better to use % and check for 0 than to compare float vs integer divisions to see if a number is easily divisible. This is because there are inaccuracies in float division that could yield some odd results. Now your bigger problem is that your testPrime function is only checking for divisibility by 29. That makes things run fast, but it limits how far up you can go before you start being wrong. The thing to do here would be to make test_prime divide by everything up to 1/2 of itself (since anything above that would result in divisibility by a lower number), and then *store the result*. If you already have a result on whether a number is prime or not, then you use that instead of recalculating it from scratch. This is a great way to keep things fast while having accuracy no matter how high up you go.

Spitfire96
 2 years ago
Best ResponseYou've already chosen the best response.0Hmm i see what you mean about the % thing ( plus it makes the code neater ) and that half of 'num' thing makes sense too. The only reason I put 2 to 9 was because I vaguely remembered something in elementary about all numbers can be divided by those numbers but I guess I'm wrong. Here is the updated version of my code, can anyone spot a problem? I love the challenge of fixing it! : #Find out which numbers are prime and which ones are not prime in a set of #numbers set by the user. print 'User, this program is used to find out which numbers in the sequence you' print 'will choose are prime and which are not prime.' print ' ' print ' ' start = int( raw_input( 'User, please enter the value you wish to start at as an iteger: ' )) stop = int( raw_input( 'now enter the value at which you wish to stop ( this value will be included in the calculations ) : ' )) def testPrime( num ) : loopSequence = 0 halfNum = num / 2 compare = False for i in range( 2, (halfNum +1)) : isPrime = num % i compare = isPrime == 0 if compare == True : break if compare == False : return 'prime' elif compare == True : return 'nonprime' for num in range( start, (stop+1)): test = testPrime(num) #print num, ' is a '+test+'number.' #this is to know if all numbers in sequence if test == 'prime': print num, ' is a '+test+' number.' #this is to know only the prime numbers

shadowfiend
 2 years ago
Best ResponseYou've already chosen the best response.1Keep in mind that returns break out of the function completely. So you could rewrite it as: def testPrime( num ) : loopSequence = 0 halfNum = num / 2 for i in range( 2, (halfNum +1)) : isPrime = num % i if isPrime == 0: return 'prime' return 'nonprime'

shadowfiend
 2 years ago
Best ResponseYou've already chosen the best response.1Heh. I swapped the prime/nonprime return values sorry.

bexica
 one year ago
Best ResponseYou've already chosen the best response.0Just my two cents: I took an introduction to programming class before several years ago and already understand many of the basics of programming. I'm taking this class to improve. That said, I found that the introductory problems given by MIT are harder than the ones at my undergrad university. They aren't just testing your ability to program, as the professor said they are testing your ability to "think computationally." Even with prior experience, I had to think hard on how to do the 1st problem set. DON'T GIVE UP. You're essentially learning two skills, programming and how to think computationally. MIT is a hard school. If you have problems, supplement the class with simple introductory programs written in other texts. Good luck and sorry for the long post!

bexica
 one year ago
Best ResponseYou've already chosen the best response.0Also, is there a problem set solution database for this course? Just curious, I am new to MIT Open Courseware too.

dgelman
 one year ago
Best ResponseYou've already chosen the best response.0In terms of the larger question posed  I can't understand how to program, I'm stuck on question one, should I stop? I'd suggest a few things. FIrst, there's no way you don't understand the basics of what it takes to program. You engage in activities every day that are "programmatic" without thinking of it. Sorting laundry is following some algorithm. You do it "mindlessly" but if you had to, you could devise some rules, put them in order, create "if this, then that or if something else, then this other thing" kinds of rules. You program every day. Yes, the hard thing is 1) being rigorous about thinking in this manner and 2) dealing with all the computer stuff. I'd suggest, if you're really stuck, starting with some programming language like Logo or some similar language. In Logo, your programs are directions to a pointer (often, historically, shaped like a turtle) like "move ahead 20, turn left 20 degrees, turn left 20, etc" and you see the line drawn by these actions on the screen. You can do some pretty amazing things with this simple language; if you've ever played with Spirograph as a kid, that's the kind of output you can get. The best part is that the language is straightforward, but the lessons learned are in _thinking_ programmatically and can be applied to any language, Python or otherwise. I'm sorry I don't have a direct link to something interesting, but try here: http://el.media.mit.edu/logofoundation/resources/links.html
Ask your own question
Sign UpFind more explanations on OpenStudy
Your question is ready. Sign up for free to start getting answers.
spraguer
(Moderator)
5
→ View Detailed Profile
is replying to Can someone tell me what button the professor is hitting...
23
 Teamwork 19 Teammate
 Problem Solving 19 Hero
 Engagement 19 Mad Hatter
 You have blocked this person.
 ✔ You're a fan Checking fan status...
Thanks for being so helpful in mathematics. If you are getting quality help, make sure you spread the word about OpenStudy.