Primality Test
Algorithm · Core
Step through it: Number Theory pattern
Step 1 of 5
Goal: the greatest common divisor of 48 and 18. Key fact: the answer stays the same if you replace (a, b) with (b, the remainder of a ÷ b). The numbers shrink quickly.
Step 2 of 5
48 ÷ 18 leaves remainder 12, so carry on with (18, 12).
Step 3 of 5
18 ÷ 12 leaves 6: carry on with (12, 6).
Step 4 of 5
12 ÷ 6 leaves 0, so stop: the answer is 6. Remainders shrink fast, so only a few steps (O(log n)). The least common multiple follows: lcm = a × b ÷ gcd. These are number theory tools.
Step 5 of 5
Your turn.
A prime number (or a prime) is a natural number greater than 1 that
cannot be formed by multiplying two smaller natural numbers. A natural number
greater than 1 that is not prime is called a composite number. For
example, 5 is prime because the only ways of writing it as a
product, 1 × 5 or 5 × 1, involve 5 itself. However, 6 is
composite because it is the product of two numbers (2 × 3) that are
both smaller than 6.
A primality test is an algorithm for determining whether an input number is prime. Among other fields of mathematics, it is used for cryptography. Unlike integer factorization, primality tests do not generally give prime factors, only stating whether the input number is prime or not. Factorization is thought to be a computationally difficult problem, whereas primality testing is comparatively easy (its running time is polynomial in the size of the input).
Code
/**
* @param {number} number
* @return {boolean}
*/
export default function trialDivision(number) {
// Check if number is integer.
if (number % 1 !== 0) {
return false;
}
if (number <= 1) {
// If number is less than one then it isn't prime by definition.
return false;
}
if (number <= 3) {
// All numbers from 2 to 3 are prime.
return true;
}
// If the number is not divided by 2 then we may eliminate all further even dividers.
if (number % 2 === 0) {
return false;
}
// If there is no dividers up to square root of n then there is no higher dividers as well.
const dividerLimit = Math.sqrt(number);
for (let divider = 3; divider <= dividerLimit; divider += 2) {
if (number % divider === 0) {
return false;
}
}
return true;
}References
Practice
Number Theory
- Greatest Common Divisor of StringsEasy
- Ugly NumberEasy
- Happy NumberEasy
- Plus OneEasy
- Add BinaryEasy
- Excel Sheet Column NumberEasy
- Count PrimesMedium
- Pow(x, n)Medium
- Factorial Trailing ZeroesMedium
- Ugly Number IIMedium
- Multiply StringsMedium
- Divide Two IntegersMedium
- Water and Jug ProblemMedium
- Super PowMedium
- Largest Component Size by Common FactorHard
Spotted a mistake or something unclear? Report it on GitHub.