Created
March 11, 2018 21:47
-
-
Save andrewphillipdoss/05a04388beb421da4dfb39f4764b44f5 to your computer and use it in GitHub Desktop.
Write an efficient script that prints largest Prime number that is smaller than 1,000,000
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def largest_prime_under(n): | |
while n >= 2: #exit loop when all iterations have been exhausted | |
# If a number is not prime, it can be factored into two factors (let's call them x and y). | |
# If both x and y are greater than the square root of n, then x*y > n, | |
# so at least one of those factors must be less than or equal to the square root of n, | |
# and to check if n is prime, we only need to test for factors less than or equal to the square root: | |
if all(n % x for x in range(2, int(n ** 0.5 + 1))): | |
print (n) #print and break if the test passes | |
break | |
n -= 1 #iterate to the next lowest number | |
largest_prime_under(1000000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment