I am having trouble doing the problem set 1 problem 1 with the prime numbers. I have been trying to use the while statement but i have been having trouble getting it to work. I must be over complicating it. Any help is appreciated.
Paste your code at codepad.org or pastebin and we will be able to help you out :-) The key thing to remember is to increment the variable inside the while loop.
Just did this one last night. Can you post your logic (algorithm written in plain english). if you get that right, the rest is cake.
I was able to see your code. I don't see how your while loop would ever end. You keep looping while incl>0 and then you increment incl. This would never be smaller than 0 (which is what you'd need to exit the loop). My logic was to take each number (which I called candidate) and I checked to see if it was odd or even. if it was even, I skipped it, but if it was odd, then I checked if it was prime or not). If it was prime then I incremented primeCount and printed it. Once primeCount was 1000, I exited the program.
could you post the code?
Also, notice that it should be a += 1, not a == a + 1 (this is a boolean expression, the former an assignment statement). One other thing, avoid asking for the actual code from other people. Try to reason on the logic that was said and how you would implement it in a program. Try to write a function that correctly checks whether or not a given number is prime (and only one), then you will try to assemble other pieces of your code. Break it in smaller problems, rather than trying to tackle the whole thing at once.
Here's my code: # Problem Set 1 # Name: John Pena # Collaborators primeCount = 1 nonPrimeCount = 0 candidate = 0 prime = 0 # Loop through candidates while primeCount <= 1000: if (candidate / 2) * 2 <> candidate : # if candidate is odd primeCheckDivisor = 2 # start with two because we know 1 will never have a remainder prime = 1 # assume the number is prime and prove otherwise #loop through possible factors until you've exhausted them all or until one divides evenly while primeCheckDivisor < candidate and prime == 1: if candidate % primeCheckDivisor == 0: # if no remainder --> not prime prime = 0 primeCheckDivisor = primeCheckDivisor + 1 # increment the divisor if prime == 1: print str(candidate) + ' is the ' + str(primeCount) + 'th prime number' primeCount = primeCount + 1 else: # candidate is not prime nonPrimeCount = nonPrimeCount + 1 candidate = candidate + 1 else: candidate = candidate + 1 print 'There are ' + str(nonPrimeCount) + ' non-prime numbers between 1 and 1000.'
Join our real-time social learning platform and learn together with your friends!