For problem set 1 question 1, I'm trying to build a program that prompts the user for a desired prime, then finds and prints that prime. From what I can tell, the list of primes isn't getting built, but I can't figure out why. Any ideas? Thanks in advance!
here's my code: inputnumprime = raw_input("Which prime would you like? i.e. for the third prime, enter 3.") #creates stopping point based on user entry inputnumprime = int(inputnumprime) #conver the user input from a string to an integer if inputnumprime == 1: print 2 else: primes = [] #creates empty list of primes count = 2 #starts count at 1 to include the number 2 primecandidate = 3 #starts at first possible prime after 2 numbers = range(0, primecandidate) #creates list of possible numbers while (count<(inputnumprime)): #run the test as long as we haven't reached the prime that the user is looking for for divisor in range(2,(int(primecandidate**0.5) + 1),2): #dynamically creates a list of factors to test if primecandidate%divisor==0: #is the prime candidate divisible by any of the factors? primecandidate = primecandidate + 2 #if so, increase the candidate by 2 to get to the next odd number else: list.append(primes) #otherwise, add it to the list of primes and count = count + 1 #and increase the count primecandidate = primecandidate + 2 #and increase the candidate by 2 to try the next one print primes[-1] #print the last prime number to tell the user their desired prime
i would start out with an empty list or a tuple such as primes = () then find out if a range of numbers are odd or even, if odd find out if they are prime numbers. just keep breaking these down, like if they're odd and less than 9 you know its a prime so just go ahead and print those, if it's odd and greater than 9 find out if it is prime. (all of this can be done in one for statement btw) that's how i did mine anyways
Try this: #Problem Set 1 - Problem 1 #Name: Username53 #Collaborators: None #Time: 2 days n = int(raw_input("Which Prime do you want? ")) counter = 1 prime = 3 total = n while (counter < total): divisor = prime/2 while (divisor > 1): if prime % divisor == 0: prime = prime + 2 divisor = prime / 2 else: divisor = divisor - 1 counter = counter + 1 prime = prime + 2 print prime - 2
Join our real-time social learning platform and learn together with your friends!