Jump to content

User:Milanand/Python 3 Programming/Conditional Statements/Solution

From Wikibooks, open books for an open world
# Solution to Exercise 2
#
# State variables
primesLeft = 999 # we already know 2 is prime
lastPrime = 2
currentCandidate = 3
testBy = 3
isPrime = True
while(primesLeft>0):
    # this approximates the square root of a number using Heron's algorithm
    g = 1
    while(currentCandidate-g*g>1):
        g=(g+currentCandidate/g)/2
    # after the square root, every divisor corresponds to a smaller quotient, checked earlier
    while(testBy-1<g):
        if currentCandidate%testBy == 0:
            isPrime = False
        testBy = testBy + 1
    # updates the state variables
    if isPrime == True:
        lastPrime = currentCandidate
        primesLeft = primesLeft - 1
    currentCandidate = currentCandidate + 2
    isPrime = True
    testBy = 3
print(lastPrime, 'is the 1000th prime number')