numerical-collection-cpp 0.10.0
A collection of algorithms in numerical analysis implemented in C++
Loading...
Searching...
No Matches
greatest_common_divisor.h
Go to the documentation of this file.
1/*
2 * Copyright 2023 MusicScience37 (Kenta Kabashima)
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
20#pragma once
21
26
27namespace num_collect::util {
28
37template <base::concepts::integral T>
38[[nodiscard]] constexpr auto greatest_common_divisor(T a, T b) -> T {
39 NUM_COLLECT_PRECONDITION(a > static_cast<T>(0) && b > static_cast<T>(0),
40 "greatest_common_divisor requires positive integers.");
41 while (true) {
42 const T x = a % b;
43 if (x == static_cast<T>(0)) {
44 return b;
45 }
46 a = b;
47 b = x;
48 }
49}
50
51} // namespace num_collect::util
Definition of exceptions.
Definition of integral concept.
Definition of macros for logging.
Namespace of utilities.
Definition assert.h:30
constexpr auto greatest_common_divisor(T a, T b) -> T
Calculate the greatest common divisor.
Definition of NUM_COLLECT_PRECONDITION macro.
#define NUM_COLLECT_PRECONDITION(CONDITION,...)
Check whether a precondition is satisfied and throw an exception if not.