Skip to content

Commit 4b72361

Browse files
dzarukinkarturov
authored andcommitted
common: math_utils: introduce an is_prime function
1 parent 74a343b commit 4b72361

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

src/common/math_utils.hpp

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*******************************************************************************
2-
* Copyright 2017-2023 Intel Corporation
2+
* Copyright 2017-2024 Intel Corporation
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -17,6 +17,8 @@
1717
#ifndef COMMON_MATH_UTILS_HPP
1818
#define COMMON_MATH_UTILS_HPP
1919

20+
#include <type_traits>
21+
2022
#include <math.h>
2123
#include <stdint.h>
2224

@@ -28,6 +30,22 @@ namespace dnnl {
2830
namespace impl {
2931
namespace math {
3032

33+
// Algorithm is picked from https://en.wikipedia.org/wiki/Primality_test
34+
template <typename T>
35+
inline bool is_prime(T n) {
36+
static_assert(std::is_integral<T>::value == true, "Not an integral type");
37+
38+
if (n <= 1 || n % 2 == 0 || n % 3 == 0 || n % 5 == 0) return false;
39+
40+
const T sqrtn = static_cast<T>(std::sqrt(n));
41+
// It is enough to check prime divisors up to `sqrt(n)`.
42+
// All potential prime divisors are represented with `6*i + k` for k={1, 5}.
43+
for (T i = 1; 6 * i + 5 <= sqrtn; i++) {
44+
if ((n % (6 * i + 1) == 0) || (n % (6 * i + 5) == 0)) return false;
45+
}
46+
return true;
47+
}
48+
3149
template <typename T>
3250
inline T gcd(T a, T b) {
3351
a = impl::nstl::abs(a);

0 commit comments

Comments
 (0)