need help with problem set 1, problems 1 and 2. no idea how to start...

At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.
Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus.
Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.

Get our expert's

answer on brainly

SEE EXPERT ANSWER

Get your **free** account and access **expert** answers to this

and **thousands** of other questions.

- anonymous

need help with problem set 1, problems 1 and 2. no idea how to start...

- jamiebookeater

I got my questions answered at brainly.com in under 10 minutes. Go to brainly.com now for free help!

Get this expert

answer on brainly

SEE EXPERT ANSWER

Get your **free** account and access **expert** answers to this

and **thousands** of other questions

- anonymous

hey what is the problem you're having? have you installed the python environment?

- anonymous

I've installed python just not sure how to tackle this problem.. managed to do problem set 0 already

- anonymous

ok cool. the main thing is, what do all numbers besides 2 have in common?

Looking for something else?

Not the answer you are looking for? Search for more explanations.

## More answers

- anonymous

let me show you what I've had, commented, maybe that will help

- anonymous

then you can work through 1b

- anonymous

ok sounds good

- anonymous

so here's the setup, at the top of your python file
## This program asks the user how many prime numbers to display. Two methods are available to
## calculate the primes. The inefficient version checks the divisibility of every number < MaxPrime
## (user input) against MaxPrime. The efficient version stops checking if any number < MaxPrime is
## divisible. I built in a variable to count the number of iterations each method must go through in
## order to check the efficiency. I used Python 2.4, the one used in this course.
PrimeCounter = 1
MaxPrime = 1
OddNumber = 1
IsPrime = 1
Primes = [2]
Counter = 2
IterCount = 0
## Get user input and initialize counter:
print "How many primes do you want to see?"
MaxPrime = int(raw_input("#>>"))

- anonymous

this explains what the program does, and the basic algorithm used.
then you ask the user for which prime they want

- anonymous

## Problem Set 1a
tan x
## This program asks the user how many prime numbers to display. Two methods are available to
## calculate the primes. The inefficient version checks the divisibility of every number < MaxPrime
## (user input) against MaxPrime. The efficient version stops checking if any number < MaxPrime is
## divisible. I built in a variable to count the number of iterations each method must go through in
## order to check the efficiency. I used Python 2.4, the one used in this course.
PrimeCounter = 1
MaxPrime = 1
OddNumber = 1
IsPrime = 1
Primes = [2]
Counter = 2
IterCount = 0
## Get user input and initialize counter:
print "How many primes do you want to see?"
MaxPrime = int(raw_input("#>>"))
while PrimeCounter < MaxPrime:
OddNumber += 2
IsPrime = 1
Counter = 2
## This the efficient version of the algorithm:
while IsPrime == 1 and Counter < OddNumber:
IterCount += 1
if OddNumber % Counter == 0:
IsPrime = 0
Counter += 1
## This is the inefficient version:
## for i in range(2, OddNumber):
## if OddNumber % i == 0:
## IsPrime = 0
## IterCount += 1
## I used a list instead of a tuple, because I can't figure out tuples.
if IsPrime == 1:
Primes += [OddNumber]
PrimeCounter += 1
## Display output. This step is not strictly necessary, but I used it to check the algorithm's accuracy.
print Primes
print "Iterations: ", IterCount

- anonymous

...........?

- anonymous

I'd try to get it running on your system. And just with the commented out inefficient version

- anonymous

ok then

- sandra

here, this version may be easier to understand than that (warning compact!)
import math ##Import square root function
testnumber = 3 ##testnumber is the number to check for primeness; 3 is the first prime after 2, so we initialize it to 3
primerank = 2 ##We want to get this to 1000
maxprime = input('What prime are you looking for? ')
while primerank <= maxprime:
divisor = 2 ##We devide by this number to check for primeness
while divisor <= math.sqrt(testnumber): ##If the testnumber is not divisible by any integer less than or equal to its square root, it is prime.
if testnumber%divisor == 0: ##This checks divisibility. If testnumber is divisible by the divisor, it cannot be prime.
testnumber = testnumber+2 ##moves on to next odd number (Even numbers can't be prime.)
divisor = 2 ##Resets divisor
else: ##If testnumber was not divisible...
divisor = divisor+1 ##...we move on to the next divisor.
##The while loop ends, meaning testnumber is the next prime.
if primerank == maxprime: ##If testnumber is the 1000th prime...
print testnumber ##...let's see it!
primerank = primerank+1
else: ##Otherwise, lets check the next odd number.
primerank = primerank+1

- sandra

^^ I highly suggest copying/pasting this into your code editor/text editor. The indentation and lack of space hamper readability of python a bit.

- anonymous

confused.com is written on my forehead right now

- anonymous

haha , it always starts that way. I would start by copying and pasting what sandra wrote into notepad or something

- anonymous

but as far as the logic goes. in Sandra's version "testNumber" is a variable that keeps track of which numbers you've checked to be prime

- anonymous

primerank is the number of primes you want to find before your program quits

- anonymous

sorry, maxprime is the number you want to find, primerank is the number your program as found during its run

- anonymous

so the first "while" loop is the main control statement. basically it says "don't quit trying until we've found the requested prime number". i.e., when primerank is equal to maxprime

- anonymous

so everything within that "while block" will be executed repeatedly until that condition is false

- anonymous

(which means you've found the prime number you want)

- anonymous

wow thats a lot to take in

- anonymous

now within that while loop, is another loop - the inner while loop basically checks the next odd number that hasn't been checked (since even numbers can't be prime). it does this by attempting to divide that number by every number between 2 and its square root (weird property of prime numbers). if that division has no remainder for any of those numbers (hence the inner while loop), then we know we've found the next prime

- anonymous

and so we move on to finding the next, until we've found the one requested by the user (maxprime)

- anonymous

yes it's a lot to take in

- anonymous

but honestly , this is the hardest part about getting started programming

- anonymous

is there an example code i could look at?

- anonymous

getting to know the actual control structures that allow you to code logic

- anonymous

control statements being things like while/for/if

- anonymous

the code that sandra wrote works for 1a

- anonymous

copy and paste it into your text editor, and then run the program
it should work

- anonymous

how do you use that code?

- anonymous

no matter what number i enter when i prompts me to, it comes out with 3

- anonymous

i tried to do this... can you point out whats wrong with it...
n = raw_input ('What number do you want to test ')
print n
if 'n'/2.0 == n/2 and n/n == 1:
print 'test number is not prime'
else: print 'test number is prime'

- anonymous

well in that case, let's take 3

- anonymous

or rather, let's take 5

- anonymous

sorry, problem with that code is you need to cast the input to an int

- anonymous

when it comes from the command line, it comes in as a string

- anonymous

well what is the actual goal of 1a?

- anonymous

so your first line should be:
n = int(raw_input ('What number do you want to test '))

- anonymous

and then it works

- anonymous

the actual goal of 1a is to find the nth prime, depending on what number the user enters

- anonymous

well then this program should work:
n = int(raw_input ('What number do you want to test '))
print n
if (n/2.0) == (n/2) and (n/n) == 1 and n !=2:
print 'test number is not prime'
else: print 'test number is prime'

- anonymous

is it not working for you?

- anonymous

no it does work.. does is solve problem 1a?

- anonymous

no ok I get it

- anonymous

what you've done is written a program that takes in a number and determines whether or not it is prime

- anonymous

okay

- anonymous

the goal is to take in a number and find *that* prime in the sequence of prime. so if you user enters "3", your program should print the third prime (5)

- anonymous

if the user enters "10", your program should print the 10th smallest prime number (29)

- anonymous

ok i understand

- anonymous

ok one problem with your first program. what happens if you enter 21?

- anonymous

well thats a problem

- anonymous

fixed problem in code, works just fine to my knowledge

- anonymous

johnny5, could you explain why you have an iteration counter? i came up with something that is more or less the same code (yours is simpler but mine works!) and i was looking at your code to see how to simplify mine (which would be easy now that i understand it), but i don't understand why or what your iteration counter was doing.

- python

k1e4v, johnny5 used the iteration counter to show the efficiency of the two different methods of printing prime numbers.

- anonymous

ah i see, so it tallies the number of divisors checked (which is more or less the marker of efficiency for this program)?

- python

yes

- anonymous

username19's function is flawed. It only tests to see if the number is divisible by 2 only. Also when is n/n != 1? Below is a function I wrote to return True if n is a prime and False if it is not.
def PrimeTest(n):
if n < 2:
return False
for i in range(2, (n/2+1)):
if n % i == 0:
return False
return True

- anonymous

SPOILER ALERT - answer below:
So I just wrote a second function that uses PrimeTest (in my last post) to finish the exercise:
def PrimeCount(n):
primesFound = 0
lastPrime = 0
testNum = 0
while primesFound < n:
if PrimeTest(testNum):
#below is executed if testNum is a true Prime number.
lastPrime = testNum
primesFound = primesFound + 1
testNum = testNum + 1
else:
testNum = testNum + 1
print "primesFound: " + str(primesFound)
print "lastPrime: " + str(lastPrime)

- anonymous

If you want to play around with these functions, copy them into a file called probset1.py and save it into your python path (where you can import py files from). Then fire up your interpreter and run:
import probset1
probset1.PrimeCount(1000)
if you want to play around with the functions (I suggest adding some print statements for debug so you can see it work) make sure to restart the interpreter after you save the probset.py file.

- anonymous

Can someone clue me into why this program isn't working? I'm trying to print numbers not divisible by 2, 3, 5, 7 and 11 (assuming they will be prime) up to the first 1000 primes.
#This is a program to print the first 1000 prime numbers.
iteration = 1
testNum = 3
while (iteration<1001): #continue to iterate until you have reached the first 1000 primes.
if testNum == 3: #exception for 3 since 3%3=0
testNum == testNum+2
iteration = iteration+1
print testNum
elif testNum == 5: #exception for 5
iteration = iteration+1
testNum == testNum+2
print testNum
elif testNum == 7: #exception for 7
iteration = iteration+1
testNum == testNum+2
print testNum
elif testNum == 11: #exception for 11
iteration = iteration+1
testNum == testNum+2
print testNum
if testNum%3 == 0:
iteration = iteration+1
testNum == testNum+2
elif testNum%5 == 0:
iteration = iteration+1
testNum == testNum+2
elif testNum%7 == 0:
iteration = iteration+1
testNum == testNum+2
elif testNum%11 == 0:
iteration = iteration+1
testNum == testNum+2
else: print testNum
testNum == testNum+2
iteration = iteration+1

- anonymous

oh btw that "if testNum%3 == 0:" half way down should be "elif" not "if"

- shadowfiend

Inside the if statements, you're saying testNum == testNum+2, which is a test, not an assignment. testNum == testNum+2 is a check to see if they are equal, and evaluates to False. You want testNum = testNum+2 (note the single equals sign).

- anonymous

Thanks for catching that shadowfiend. I know this is not the solution for prob set 1 though and have fixed it so it works. Thanks!

- shadowfiend

Good to hear! Glad to help.

- anonymous

do you guys read or watch other stuff about python because you're using some stuff I haven't seen in the lecture videos...

- anonymous

has anyone solved this problem? i have a working version of it that i was able to put together using function but i'm not able to do it just using the while and if statements

- anonymous

Hi!
What have you got so far?

- anonymous

here is what i got so far i think i got it done to calculate prime numbers only but i think what i'm doing wrong is not putting the addition in the right price to get the counter up or something
from math import sqrt
testNumb = 1
counter = 2
divisor = 1
maxPrime = int(raw_input ('Enter a number for to get that prime '))
if maxPrime == 1:
print 2
elif maxPrime==2:
print 3
else:
while (counter < maxPrime):
while(divisor < int(sqrt(testNumb)+1)):
if (testNumb % divisor ==0):
testNumb += 2
else:
divisor +=1
counter +=1
divisor += 2
testNumb += 2
print testNumb

- anonymous

right place** lol

- anonymous

ok so i found out whats wrong it is the counter ever time it goes thru the loop it raises what is added to the counter so it goes counter + 1 then counter + 2 then counter +3 i dont know why its doing that

- anonymous

First, it's good that you've accounted for the first and 2nd prines, but because you've done that, where should you start checking for new primes? In the current program, you're starting at testNumb = 1

- anonymous

i was playing around with that just because of the results so when i changed testNumb = 3 if i test for 3rd prime i will get 13

- anonymous

ok i think i fixed the counter problem with this but now i realized sometimes it is allowing multiples of 5 to be counted
from math import sqrt
testNumb = 3
counter = 2
divisor = 3
maxPrime = int(raw_input ('Enter a number for to get that prime '))
if maxPrime == 1:
print 2
elif maxPrime==2:
print 3
else:
while (counter < maxPrime):
testNumb += 2
while(divisor < int(sqrt(testNumb)+1)):
if (testNumb % divisor ==0):
testNumb += 2
else:
divisor +=1
divisor += 2
counter +=1
print testNumb

- anonymous

There's an issue in the initial values, but what they should be depends on how the rest of the program is structured.
First, we've got this:
else:
while (counter < maxPrime):
while(divisor < int(sqrt(testNumb)+1)):
if (testNumb % divisor ==0):
testNumb += 2
else:
divisor +=1
counter +=1
divisor += 2
testNumb += 2
print testNumb
Try going through this program line by line. What happens to the flow of control after the statements
if (testNumb % divisor ==0):
testNumb += 2
What is the value of the divisor and what happens to it?

- anonymous

Another way of asking the same question is: When you start testing a new testNumb, what number do you want the divisor to be?

- anonymous

yeah i get what you are saying i should have a place where if the number is prime to set the divisor back to the initial value right?

- anonymous

I would think that every time the testNumb changed, you'd want to reset the divisor. For instance, if one number is divisible by 7 (not prime) the next testNumb will be (oldtestNumb +2). If you only reset the divisor when a number is prime, you're going to start trying to divide the new testNumb by 9.

- anonymous

yeah i totally didnt check for that or even thought about the divisor to set it back thanks a lot Somna :) its working great now
from math import sqrt
testNumb = 3
counter = 2
divisor = 3
maxPrime = int(raw_input ('Enter a number for to get that prime '))
if maxPrime == 1:
print 2
elif maxPrime==2:
print 3
else:
while (counter < maxPrime):
testNumb += 2
divisor = 3
while(divisor < int(sqrt(testNumb)+1)):
if (testNumb % divisor ==0):
testNumb += 2
divisor = 3
else:
divisor +=1
divisor = 3
counter +=1
print testNumb

- anonymous

nice!

- anonymous

yeah thanks now time to revise and make it better lol

- anonymous

I think what is important is that you read on how to find prime numbers without mathematics first. This will point anyone in the correct direction. ex. http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes. From there you can easily create a loop, or for sequence to calculate any primes up to any number. Then if you create a list of them, without using captain 119's code, you can just list the index for any value - 1. ex. For prime # 777 in a list of 1000 prime numbers, just ask to show index for 776...my guess is that it should work without complicated code.

- anonymous

ps. Not bashing captain 119 in any way...I am just a rookie and just thought there should be something simpler...

- anonymous

- anonymous

- anonymous

Hi - sorry about this reposting...for some reason everytime I login this posts...I am not sure why...

- anonymous

- shadowfiend

Hm. We'll look at that. That's a problem on our end :)

Looking for something else?

Not the answer you are looking for? Search for more explanations.