Taskintro
Check whether a number is prime
Also called is prime, primality test, prime check, trial division, isPrime, isProbablePrime, ProbablyPrime, math.isqrt.
Check whether an integer is prime with trial division up to its square root, and use a library test for big numbers. Numbers below 2 are not prime.
- Evidence
- Code in 10 languages
Task
Check whether an integer is prime. A prime is an integer greater than 1 whose only positive divisors are 1 and itself.
The Rosetta Code task on primality by trial division says: "Write a boolean function that tells whether a given integer is prime", and "Remember that 1 and all non-positive numbers are not prime"1.
The function is_prime(n) returns true or false. For example, is_prime(17) is true, and is_prime(561) is false, because 561 is 3 times 11 times 17.
Trial division divides n by each candidate divisor. Only the candidates up to the square root of n are necessary: if n is a times b and both are larger than the square root, the product is larger than n. So the loop is:
- If
nis less than 2, the answer isfalse. Ifnis 2, the answer istrue. Ifnis even, the answer isfalse. - For each odd
ifrom 3 whilei * i <= n: ifidividesn, the answer isfalse. - The answer is
true.
The Rosetta Code task says the same: "Even numbers greater than 2 may be eliminated right away"1. The loop takes about the square root of n divided by 2 steps. For n near 2 to the power 31, that is about 23000 steps.
The items are 64-bit signed integers, and the cases are small enough for trial division. For a number with 19 digits, trial division takes about 1.5 billion steps, so use a library test, as the solutions show.
Solutions
| Language | Trial division | Library test for big numbers |
|---|---|---|
| Python | math.isqrt(n) as the bound |
none in the standard library |
| JavaScript, TypeScript | BigInt values, i * i <= n |
none |
| Java | i <= n / i |
BigInteger.isProbablePrime(certainty) |
| C# | i <= n / i |
none |
| Go | i <= n/i |
big.Int.ProbablyPrime(0) |
| Rust | i <= n / i |
none in the standard library |
| C | i <= n / i |
none |
| C++ | i <= n / i |
none |
| Bash | $((i * i <= n)) |
none |
- Python.
math.isqrt(n)returns "the floor of the exact square root of n, or equivalently the greatest integer a such that a² ≤ n"2. It is exact for each size of integer, butmath.sqrtreturns a float, which is not exact for large numbers. - JavaScript. There is no prime test. The solution uses
BigIntvalues, because anumbercannot hold each 64-bit integer. - TypeScript. The same code as JavaScript, with the type
bigint. - Java.
BigInteger.isProbablePrime"Returns true if this BigInteger is probably prime, false if it's definitely composite"3. The argumentcertaintysets the error: if the call returns true, "the probability that this BigInteger is prime exceeds (1 - 1/2certainty)"3, that is, 1 minus 1 divided by 2 to the powercertainty. - C#. There is no prime test in the standard library. The solution uses trial division.
- Go.
ProbablyPrimeapplies "the Miller-Rabin test with n pseudorandomly chosen bases as well as a Baillie-PSW test", and it "is 100% accurate for inputs less than 2⁶⁴"4. Sobig.NewInt(n).ProbablyPrime(0)is an exact test for eachint64value. - Rust. The standard library has no prime test. The solution uses trial division.
- C. The solution uses trial division with
long longvalues. - C++. The solution uses trial division with
long longvalues. - Bash. The solution uses a
whileloop with$((n % i)), and returns the exit status 0 for a prime and 1 for other numbers.
The Python solution, with the primes below 30:
import math
def is_prime(n):
if n < 2:
return False
if n % 2 == 0:
return n == 2
for i in range(3, math.isqrt(n) + 1, 2):
if n % i == 0:
return False
return True
print([n for n in range(30) if is_prime(n)])
print(is_prime(2147483647), is_prime(561))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
True False
The library test in Go is exact for each 64-bit value. 9223372036854775783 is the largest prime below 2 to the power 63:
package main
import (
"fmt"
"math/big"
)
func main() {
fmt.Println(big.NewInt(9223372036854775783).ProbablyPrime(0))
fmt.Println(big.NewInt(9223372036854775781).ProbablyPrime(0))
fmt.Println(big.NewInt(561).ProbablyPrime(0))
}
true
false
false
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
small-prime,small-composite,evenandodd-composite: the simple cases.negative,zeroandone: numbers below 2 are not prime.two: the only even prime.three: the first odd prime; the loop does not run.square-of-primeandlarge-square: 25 is 5 times 5, and 4293001441 is 65521 times 65521. A loop that stops before the square root misses the divisor.carmichael: 561 is not prime, but it passes the Fermat test for each base that is coprime to it.large-prime,mersenne-primeandlarge-composite: 1000000007 and 2147483647 are prime, and 2147483649 is 3 times 715827883.
Pitfalls
-
The loop stops one step early. The bound includes the square root. With
i * i < nin place ofi * i <= n, the square of a prime, such as 25, is wrongly prime. -
The square overflows.
i * ican be larger than the largest value of the type. In 32-bit arithmetic, 46341 squared does not fit, and the result is negative, soi * i <= nis true again. Compare withi <= n / i, or use a wider type:
This code runs but gives a wrong answer on purpose.
package main
import "fmt"
func main() {
var i int32 = 46341
fmt.Println(i*i, int64(i)*int64(i))
}
-2147479015 2147488281
-
A float square root is not exact.
math.sqrt(n)returns a float, and a 64-bit float has 53 bits of precision. For a largen, the rounded root can be 1 too small, and the loop misses the last divisor. Use an integer square root, such asmath.isqrtin Python, or the comparisoni <= n / i. -
The Fermat test is not a prime test. If
nis prime, thenato the powern - 1is 1 modulon. The reverse is false: "Some composite numbers (Carmichael numbers) have the property"5 for each baseathat is coprime ton. 561 is the smallest of them:
print(pow(2, 560, 561), pow(5, 560, 561), 561 % 3)
1 1 0
Use a library test, such as isProbablePrime in Java or ProbablyPrime in Go. They combine tests such as Miller-Rabin and the Baillie-PSW test, which "has no known counterexamples"5.
- A prime test in a loop is slow. To find all primes up to a limit, a test for each number repeats work. A sieve marks the multiples of each prime once. See the algorithm site below.
Related tasks
- Compute the greatest common divisor: two numbers are coprime when their GCD is 1.
- Compute a factorial: another small task on integers.
- Use big integers: prime tests on numbers with no size limit.
The algorithms are on the algorithm site: trial division, the Miller-Rabin test and the sieve of Eratosthenes.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/check-whether-a-number-is-prime/.
import math
def is_prime(n: int) -> bool:
"""Return True if n is prime, with trial division up to the square root."""
if n < 2:
return False
if n % 2 == 0:
return n == 2
for i in range(3, math.isqrt(n) + 1, 2):
if n % i == 0:
return False
return True
test_prime.py 33 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/check-whether-a-number-is-prime/.
import pytest
from prime import is_prime
CASES = [
("small-prime", 17, True),
("small-composite", 15, False),
("even", 100, False),
("odd-composite", 91, False),
("negative", -7, False),
("zero", 0, False),
("one", 1, False),
("two", 2, True),
("three", 3, True),
("square-of-prime", 25, False),
("large-square", 4293001441, False),
("carmichael", 561, False),
("large-prime", 1000000007, True),
("mersenne-prime", 2147483647, True),
("large-composite", 2147483649, False),
]
@pytest.mark.parametrize(("name", "n", "want"), CASES, ids=[c[0] for c in CASES])
def test_is_prime(name, n, want):
assert is_prime(n) is want
def test_primes_below_30():
assert [n for n in range(30) if is_prime(n)] == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-number-is-prime/.
#ifndef IS_PRIME_HPP
#define IS_PRIME_HPP
// Returns true if n is prime, with trial division. i <= n / i does not
// overflow, but i * i can.
constexpr bool is_prime(long long n) {
if (n < 2) {
return false;
}
if (n % 2 == 0) {
return n == 2;
}
for (long long i = 3; i <= n / i; i += 2) {
if (n % i == 0) {
return false;
}
}
return true;
}
#endif
test_prime.cpp 51 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-number-is-prime/.
#include <cstdio>
#include "prime.hpp"
namespace {
struct test_case {
const char* name;
long long n;
bool want;
};
const test_case cases[] = {
{"small-prime", 17, true},
{"small-composite", 15, false},
{"even", 100, false},
{"odd-composite", 91, false},
{"negative", -7, false},
{"zero", 0, false},
{"one", 1, false},
{"two", 2, true},
{"three", 3, true},
{"square-of-prime", 25, false},
{"large-square", 4293001441LL, false},
{"carmichael", 561, false},
{"large-prime", 1000000007, true},
{"mersenne-prime", 2147483647, true},
{"large-composite", 2147483649LL, false},
};
static_assert(is_prime(97) && !is_prime(91));
} // namespace
int main() {
int failures = 0;
for (const auto& c : cases) {
if (is_prime(c.n) != c.want) {
std::printf("FAIL %s\n", c.name);
++failures;
}
}
if (failures != 0) {
return 1;
}
std::printf("ok\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-number-is-prime/.
/** A prime test with trial division. */
public final class Prime {
private Prime() {}
/** Returns true if n is prime. i <= n / i does not overflow, but i * i can. */
public static boolean isPrime(long n) {
if (n < 2) {
return false;
}
if (n % 2 == 0) {
return n == 2;
}
for (long i = 3; i <= n / i; i += 2) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
PrimeTest.java 41 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-number-is-prime/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.math.BigInteger;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class PrimeTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("small-prime", 17, true),
Arguments.of("small-composite", 15, false),
Arguments.of("even", 100, false),
Arguments.of("odd-composite", 91, false),
Arguments.of("negative", -7, false),
Arguments.of("zero", 0, false),
Arguments.of("one", 1, false),
Arguments.of("two", 2, true),
Arguments.of("three", 3, true),
Arguments.of("square-of-prime", 25, false),
Arguments.of("large-square", 4293001441L, false),
Arguments.of("carmichael", 561, false),
Arguments.of("large-prime", 1000000007, true),
Arguments.of("mersenne-prime", 2147483647, true),
Arguments.of("large-composite", 2147483649L, false)
);
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void isPrime(String name, long n, boolean want) {
assertEquals(want, Prime.isPrime(n));
if (n >= 2) {
assertEquals(want, BigInteger.valueOf(n).isProbablePrime(50));
}
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-number-is-prime/.
#include "prime.h"
bool is_prime(long long n) {
if (n < 2) {
return false;
}
if (n % 2 == 0) {
return n == 2;
}
// i <= n / i does not overflow, but i * i can.
for (long long i = 3; i <= n / i; i += 2) {
if (n % i == 0) {
return false;
}
}
return true;
}
prime.h 12 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-number-is-prime/.
#ifndef IS_PRIME_H
#define IS_PRIME_H
#include <stdbool.h>
// Returns true if n is prime, with trial division.
bool is_prime(long long n);
#endif
test_prime.c 47 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-number-is-prime/.
#include "prime.h"
#include <stdio.h>
#include <stdlib.h>
struct test_case {
const char *name;
long long n;
bool want;
};
static const struct test_case cases[] = {
{"small-prime", 17, true},
{"small-composite", 15, false},
{"even", 100, false},
{"odd-composite", 91, false},
{"negative", -7, false},
{"zero", 0, false},
{"one", 1, false},
{"two", 2, true},
{"three", 3, true},
{"square-of-prime", 25, false},
{"large-square", 4293001441LL, false},
{"carmichael", 561, false},
{"large-prime", 1000000007, true},
{"mersenne-prime", 2147483647, true},
{"large-composite", 2147483649LL, false},
};
int main(void) {
int failures = 0;
for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
const struct test_case *c = &cases[i];
if (is_prime(c->n) != c->want) {
printf("FAIL %s\n", c->name);
failures++;
}
}
if (failures != 0) {
return EXIT_FAILURE;
}
printf("ok\n");
return EXIT_SUCCESS;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-number-is-prime/.
/// <summary>A prime test with trial division.</summary>
public static class Prime
{
/// <summary>Returns true if n is prime. i <= n / i does not overflow, but i * i can.</summary>
public static bool IsPrime(long n)
{
if (n < 2)
{
return false;
}
if (n % 2 == 0)
{
return n == 2;
}
for (long i = 3; i <= n / i; i += 2)
{
if (n % i == 0)
{
return false;
}
}
return true;
}
}
PrimeTests.cs 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-number-is-prime/.
using Xunit;
public sealed class PrimeTests
{
public static TheoryData<string, long, bool> Cases => new()
{
{ "small-prime", 17, true },
{ "small-composite", 15, false },
{ "even", 100, false },
{ "odd-composite", 91, false },
{ "negative", -7, false },
{ "zero", 0, false },
{ "one", 1, false },
{ "two", 2, true },
{ "three", 3, true },
{ "square-of-prime", 25, false },
{ "large-square", 4293001441, false },
{ "carmichael", 561, false },
{ "large-prime", 1000000007, true },
{ "mersenne-prime", 2147483647, true },
{ "large-composite", 2147483649, false },
};
[Theory]
[MemberData(nameof(Cases))]
public void IsPrime(string name, long n, bool want)
{
Assert.NotNull(name);
Assert.Equal(want, Prime.IsPrime(n));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-number-is-prime/.
/** Returns true if the BigInt n is prime, with trial division. */
export function isPrime(n) {
if (n < 2n) {
return false;
}
if (n % 2n === 0n) {
return n === 2n;
}
for (let i = 3n; i * i <= n; i += 2n) {
if (n % i === 0n) {
return false;
}
}
return true;
}
prime.test.js 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-number-is-prime/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { isPrime } from "./prime.js";
const cases = [
["small-prime", 17n, true],
["small-composite", 15n, false],
["even", 100n, false],
["odd-composite", 91n, false],
["negative", -7n, false],
["zero", 0n, false],
["one", 1n, false],
["two", 2n, true],
["three", 3n, true],
["square-of-prime", 25n, false],
["large-square", 4293001441n, false],
["carmichael", 561n, false],
["large-prime", 1000000007n, true],
["mersenne-prime", 2147483647n, true],
["large-composite", 2147483649n, false],
];
for (const [name, n, want] of cases) {
test(name, () => {
assert.equal(isPrime(n), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-number-is-prime/.
/** Returns true if the bigint n is prime, with trial division. */
export function isPrime(n: bigint): boolean {
if (n < 2n) {
return false;
}
if (n % 2n === 0n) {
return n === 2n;
}
for (let i = 3n; i * i <= n; i += 2n) {
if (n % i === 0n) {
return false;
}
}
return true;
}
prime.test.ts 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-number-is-prime/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { isPrime } from "./prime.ts";
const cases: [string, bigint, boolean][] = [
["small-prime", 17n, true],
["small-composite", 15n, false],
["even", 100n, false],
["odd-composite", 91n, false],
["negative", -7n, false],
["zero", 0n, false],
["one", 1n, false],
["two", 2n, true],
["three", 3n, true],
["square-of-prime", 25n, false],
["large-square", 4293001441n, false],
["carmichael", 561n, false],
["large-prime", 1000000007n, true],
["mersenne-prime", 2147483647n, true],
["large-composite", 2147483649n, false],
];
for (const [name, n, want] of cases) {
test(name, () => {
assert.equal(isPrime(n), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-number-is-prime/.
// Package prime tests whether an integer is prime.
package prime
// IsPrime reports whether n is prime, with trial division. i <= n/i does
// not overflow, but i*i can.
func IsPrime(n int64) bool {
if n < 2 {
return false
}
if n%2 == 0 {
return n == 2
}
for i := int64(3); i <= n/i; i += 2 {
if n%i == 0 {
return false
}
}
return true
}
prime_test.go 44 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-number-is-prime/.
package prime
import (
"math/big"
"testing"
)
var cases = []struct {
name string
n int64
want bool
}{
{"small-prime", 17, true},
{"small-composite", 15, false},
{"even", 100, false},
{"odd-composite", 91, false},
{"negative", -7, false},
{"zero", 0, false},
{"one", 1, false},
{"two", 2, true},
{"three", 3, true},
{"square-of-prime", 25, false},
{"large-square", 4293001441, false},
{"carmichael", 561, false},
{"large-prime", 1000000007, true},
{"mersenne-prime", 2147483647, true},
{"large-composite", 2147483649, false},
}
func TestIsPrime(t *testing.T) {
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got := IsPrime(c.n); got != c.want {
t.Fatalf("IsPrime(%d) = %v, want %v", c.n, got, c.want)
}
if c.n >= 0 && big.NewInt(c.n).ProbablyPrime(0) != c.want {
t.Fatalf("ProbablyPrime(%d) differs", c.n)
}
})
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-number-is-prime/.
/// Returns true if n is prime, with trial division. i <= n / i does not
/// overflow, but i * i can.
pub fn is_prime(n: i64) -> bool {
if n < 2 {
return false;
}
if n % 2 == 0 {
return n == 2;
}
let mut i = 3;
while i <= n / i {
if n % i == 0 {
return false;
}
i += 2;
}
true
}
tests/prime_test.rs 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-number-is-prime/.
use algo_check_whether_a_number_is_prime::is_prime;
const CASES: &[(&str, i64, bool)] = &[
("small-prime", 17, true),
("small-composite", 15, false),
("even", 100, false),
("odd-composite", 91, false),
("negative", -7, false),
("zero", 0, false),
("one", 1, false),
("two", 2, true),
("three", 3, true),
("square-of-prime", 25, false),
("large-square", 4293001441, false),
("carmichael", 561, false),
("large-prime", 1000000007, true),
("mersenne-prime", 2147483647, true),
("large-composite", 2147483649, false),
];
#[test]
fn cases() {
for &(name, n, want) in CASES {
assert_eq!(is_prime(n), want, "{name}");
}
}
#[test]
fn primes_below_30() {
let primes: Vec<i64> = (0..30).filter(|&n| is_prime(n)).collect();
assert_eq!(primes, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]);
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/check-whether-a-number-is-prime/.
# is_prime N
# Returns the exit status 0 if N is prime and 1 if not, with trial division.
is_prime() {
local n=$1 i=3
if ((n < 2)); then
return 1
fi
if ((n % 2 == 0)); then
((n == 2))
return
fi
while ((i <= n / i)); do
if ((n % i == 0)); then
return 1
fi
i=$((i + 2))
done
return 0
}
test_prime.bats 23 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/check-whether-a-number-is-prime/.
setup() {
source "$BATS_TEST_DIRNAME/prime.sh"
}
@test "small-prime" { run is_prime 17; [ "$status" -eq 0 ]; }
@test "small-composite" { run is_prime 15; [ "$status" -eq 1 ]; }
@test "even" { run is_prime 100; [ "$status" -eq 1 ]; }
@test "odd-composite" { run is_prime 91; [ "$status" -eq 1 ]; }
@test "negative" { run is_prime -7; [ "$status" -eq 1 ]; }
@test "zero" { run is_prime 0; [ "$status" -eq 1 ]; }
@test "one" { run is_prime 1; [ "$status" -eq 1 ]; }
@test "two" { run is_prime 2; [ "$status" -eq 0 ]; }
@test "three" { run is_prime 3; [ "$status" -eq 0 ]; }
@test "square-of-prime" { run is_prime 25; [ "$status" -eq 1 ]; }
@test "large-square" { run is_prime 4293001441; [ "$status" -eq 1 ]; }
@test "carmichael" { run is_prime 561; [ "$status" -eq 1 ]; }
@test "large-prime" { run is_prime 1000000007; [ "$status" -eq 0 ]; }
@test "mersenne-prime" { run is_prime 2147483647; [ "$status" -eq 0 ]; }
@test "large-composite" { run is_prime 2147483649; [ "$status" -eq 1 ]; }
References
- Rosetta Code, Primality by trial division (task text, from acmeism/RosettaCodeData), task text
- The Python Standard Library, math.integer, isqrt
- Java SE 25 API, Class BigInteger, isProbablePrime(int)
- Go standard library, math/big, func (*Int) ProbablyPrime
- Wikipedia, Primality test, Simple methods; Fermat primality test; Baillie–PSW primality test
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag J95CT6 Edit this page History Report an error Markdown