polpak could you explain this part of the code for Pset1? while (divisor>1): if number%divisor == 0: divisor = 0 else: divisor = divisor - 1
I'm not sure where this code is from, but presuming that divisor is something like number-1 initially. It would seem to me that we are looping over each number less than 'number' and seeing if 'number' is divisible evenly by the divisor. If it is, then the number is not prime and we can stop early. Otherwise we keep going. The only difficulty is that it's impossible to know after the loop has finished whether you traversed every number, or whether you ended early. You may want to have a separate boolean variable to denote whether you end early. For example you could have this assignment before the while loop divisorFound = False then in the branch for 'if number%divisor == 0' simply set divisorFound=True Then you can tell with a simple if whether or not you managed to find a factor.
This code was used earlier in one of the other discussion threads. divisor is equal to number/2 initially.
Fair enough. It would work just as well to choose number-1. It would simply add a little extra work since none of the numbers in the range (number/2, number-1] are actually possible divisors.
I guess my question is how does that code show if the number is prime or not. I think i might be onto it now. so the code that says if number%divisor == 0 divisor = 0 ## This is saying that if this happens the divisor being used can be factored from the number thus making it not prime?
Yes, because prime numbers are only divisible by themselves and 1. if (number%divisor == 0) and (number != divisor) and (number != 1) then number is not prime The code sets divisor to 0 just as an easy way to get out of the while loop. It knows that it doesn't need to search further because we've already found for sure that number is not prime.
err the third part of the condition should be that divisor != 1 actually.
ok thanks. I saw an earlier post that i think it was you who recommended writing out what you wanted each task to accomplish. I think that as long as i can see the progression i'll be able to figure some of these out on my own now. Just needed an understanding of how to get there
Join our real-time social learning platform and learn together with your friends!