Hello guys. Starting on problem set 1, problem 1. I figured it would help me to write a function for prime numbers before I moved on to the next part of the problem. However, thats not working very well. http://dpaste.com/547820/ The issue is that a prime number, say 5, would meet the conditions i ask in the script and it would print at the end, but so would the number 4, which is not a prime number.
Hoot! You just asked your first question! Hang tight while I find people to answer it for you. You can thank people who give you good answers by clicking the 'Good Answer' button on the right!
All numbers will fit the first condition, divide anything by 1 and you are left with the same number. Divide anything by itself and there will be no remainder. Therefore, it will print x if y can't be divided into it, or it will do nothing otherwise. Your example prints 4 because you can't divide 3 into 4 (evenly), even though you can divide 2 into 4 (you are not checking for that).
I don't know if it helps, but I just finished this assignment, and the first thing I did in my function was check to see if any test number divided by either 2 or 3 had a remainder. That eliminates any even numbers and multiples of 3.
Here is what I came up with and it appears to work: def isPrime(cand): prime = None if (cand==1) or (cand%2==0 and cand!=2): prime = False else : for divisor in range(3,(cand/3+1),2): if cand%divisor==0: prime = False if prime == False: return False else: return True Calling isPrime(cand) will return either True or False eg. >>> isPrime(9) False >>> isPrime(7919) True Hope this helps :)
Join our real-time social learning platform and learn together with your friends!