Created
September 25, 2020 18:00
-
-
Save SoftwareDevPro/bad06b7836bd865daefac81a902405fd to your computer and use it in GitHub Desktop.
Is Prime in Python and Javascript, O(sqrt(num))
This file contains hidden or 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
| 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}`) | |
| } |
This file contains hidden or 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
| # 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