Skip to content

Instantly share code, notes, and snippets.

@andrewphillipdoss
Created March 11, 2018 21:47
Show Gist options
  • Save andrewphillipdoss/05a04388beb421da4dfb39f4764b44f5 to your computer and use it in GitHub Desktop.
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
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