Skip to content

Instantly share code, notes, and snippets.

@aarongeorge
Last active April 30, 2020 11:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aarongeorge/e64eb5dd907aca6b0d295d7164a6aec3 to your computer and use it in GitHub Desktop.
Save aarongeorge/e64eb5dd907aca6b0d295d7164a6aec3 to your computer and use it in GitHub Desktop.
Interview question to find all prime numbers between 0 and 100
// The definition of a prime number is a positive integer that has exactly two positive divisors (This means the divisors could only ever be 1 and the number itself)
// Given that's the case, 0 can't be a prime as you can't divide 0 by 0. Just as 1 can't be prime as 1 divided by 1 is using the same divisor.
// This means any time we want to loop to find a prime, we can ignore 0 and 1 and start at 2
// So given the definition of a prime we can write a function like this to check if a number is prime
const isPrime = n => {
for (let i = 2; i < n; i++)
if (!(n % i)) return !!0
return n > 1
}
// I could then create a loop that calls that function and logs out the number if it is prime
// for (let i = 2; i <= 100; i++) isPrime(i) && console.log(i)
// Or I could save a function call by integrating the check into the loop itself
for (let i = 2; i <= 100; i++) {
for (let j = 2; j < i; j++)
if (!(j % i)) console.log(i)
i > 1 && console.log(i)
}
// If you wanted to remove the duplication of console.log you can cache it, although it does introduce another function call and increases the filesize
// Though depending on the complexity of the cb, it might be less filesize than duplicating the cb twice like in the previous example
for (let i = 2; i <= 100; i++) {
const cb = console.log(i)
for (let j = 2; j < i; j++)
if (!(j % i)) cb(i)
(i > 1) && cb(i)
}
// I could decrease the complexity of the prime algorithm by checking if the current loop iterator is smaller than the square root of the number being tested
const isPrime2 = n => {
for (let i = 2, s = Math.sqrt(n); i < s; i++)
if (!(n % i)) return !!0
return n > 1
}
// Using this method with the previous examples we could use
for (let i = 2; i <= 100; i++) isPrime2(i) && console.log(i)
// Inline check
for (let i = 2; i <= 100; i++) {
const cb = console.log(i)
for (let j = 2, s = Math.sqrt(i); j < s; j++)
if (!(i % j)) cb(i)
(i > 1) && cb(i)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment