Skip to content

Instantly share code, notes, and snippets.

@SoftwareDevPro
Created September 25, 2020 18:00
Show Gist options
  • Select an option

  • Save SoftwareDevPro/bad06b7836bd865daefac81a902405fd to your computer and use it in GitHub Desktop.

Select an option

Save SoftwareDevPro/bad06b7836bd865daefac81a902405fd to your computer and use it in GitHub Desktop.
Is Prime in Python and Javascript, O(sqrt(num))
is_prime = (num) => {
if (num == 1) {
return false
}
let i = 2
while (i * i <= num) {
if (num % i == 0) {
return false
}
i++
}
return true
}
for(let idx = 1; idx <= 11; idx++) {
console.log(`${idx} is prime?: ${is_prime(idx}`)
}
# When finding factors of a number it is enough to iterate from 1 to sqrt(N)
# to find all the factors of N. So, from 1 to sqrt(N) we would find exactly 1
# factor, i.e. 1 itself. Iterating from 2 to sqrt(N), if we find any factor in this
# range, then we call that number a non-prime number, else it is a prime number.
def is_prime(num):
if num == 1:
return False
i = 2
while i*i <= num:
if num % i == 0:
# This means that num has a factor in between 2 and sqrt(num)
# So it is not a prime number
return False
i += 1
return True
for idx in range(1, 11):
print(f"{idx} is prime?: {is_prime(idx)}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment