1// <numeric> -*- C++ -*-
3// Copyright (C) 2001-2019 Free Software Foundation, Inc.
5// This file is part of the GNU ISO C++ Library. This library is free
6// software; you can redistribute it and/or modify it under the
7// terms of the GNU General Public License as published by the
8// Free Software Foundation; either version 3, or (at your option)
11// This library is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
16// Under Section 7 of GPL version 3, you are granted additional
17// permissions described in the GCC Runtime Library Exception, version
18// 3.1, as published by the Free Software Foundation.
20// You should have received a copy of the GNU General Public License and
21// a copy of the GCC Runtime Library Exception along with this program;
22// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23// <http://www.gnu.org/licenses/>.
28 * Hewlett-Packard Company
30 * Permission to use, copy, modify, distribute and sell this software
31 * and its documentation for any purpose is hereby granted without fee,
32 * provided that the above copyright notice appear in all copies and
33 * that both that copyright notice and this permission notice appear
34 * in supporting documentation. Hewlett-Packard Company makes no
35 * representations about the suitability of this software for any
36 * purpose. It is provided "as is" without express or implied warranty.
39 * Copyright (c) 1996,1997
40 * Silicon Graphics Computer Systems, Inc.
42 * Permission to use, copy, modify, distribute and sell this software
43 * and its documentation for any purpose is hereby granted without fee,
44 * provided that the above copyright notice appear in all copies and
45 * that both that copyright notice and this permission notice appear
46 * in supporting documentation. Silicon Graphics makes no
47 * representations about the suitability of this software for any
48 * purpose. It is provided "as is" without express or implied warranty.
51/** @file include/numeric
52 * This is a Standard C++ Library header.
55#ifndef _GLIBCXX_NUMERIC
56#define _GLIBCXX_NUMERIC 1
58#pragma GCC system_header
60#include <bits/c++config.h>
61#include <bits/stl_iterator_base_types.h>
62#include <bits/stl_numeric.h>
63#include <ext/numeric_traits.h>
65#ifdef _GLIBCXX_PARALLEL
66# include <parallel/numeric>
70 * @defgroup numerics Numerics
72 * Components for performing numeric operations. Includes support for
73 * complex number types, random number generation, numeric (n-at-a-time)
74 * arrays, generalized numeric algorithms, and mathematical special functions.
77#if __cplusplus >= 201402L
80namespace std _GLIBCXX_VISIBILITY(default)
82_GLIBCXX_BEGIN_NAMESPACE_VERSION
86 // std::abs is not constexpr, doesn't support unsigned integers,
87 // and std::abs(std::numeric_limits<T>::min()) is undefined.
88 template<typename _Up, typename _Tp>
92 static_assert(is_unsigned<_Up>::value, "result type must be unsigned");
93 static_assert(sizeof(_Up) >= sizeof(_Tp),
94 "result type must be at least as wide as the input type");
95 return __val < 0 ? -(_Up)__val : (_Up)__val;
98 template<typename _Up> void __absu(bool) = delete;
100 // GCD implementation
101 template<typename _Tp>
103 __gcd(_Tp __m, _Tp __n)
105 static_assert(is_unsigned<_Tp>::value, "type must be unsigned");
106 return __m == 0 ? __n
108 : __detail::__gcd(__n, _Tp(__m % __n));
111 // LCM implementation
112 template<typename _Tp>
114 __lcm(_Tp __m, _Tp __n)
116 return (__m != 0 && __n != 0)
117 ? (__m / __detail::__gcd(__m, __n)) * __n
120} // namespace __detail
122#if __cplusplus >= 201703L
124#define __cpp_lib_gcd_lcm 201606
125// These were used in drafts of SD-6:
126#define __cpp_lib_gcd 201606
127#define __cpp_lib_lcm 201606
129 /// Greatest common divisor
130 template<typename _Mn, typename _Nn>
131 constexpr common_type_t<_Mn, _Nn>
132 gcd(_Mn __m, _Nn __n) noexcept
134 static_assert(is_integral_v<_Mn>, "std::gcd arguments must be integers");
135 static_assert(is_integral_v<_Nn>, "std::gcd arguments must be integers");
136 static_assert(_Mn(2) != _Mn(1), "std::gcd arguments must not be bool");
137 static_assert(_Nn(2) != _Nn(1), "std::gcd arguments must not be bool");
138 using _Up = make_unsigned_t<common_type_t<_Mn, _Nn>>;
139 return __detail::__gcd(__detail::__absu<_Up>(__m),
140 __detail::__absu<_Up>(__n));
143 /// Least common multiple
144 template<typename _Mn, typename _Nn>
145 constexpr common_type_t<_Mn, _Nn>
146 lcm(_Mn __m, _Nn __n) noexcept
148 static_assert(is_integral_v<_Mn>, "std::lcm arguments must be integers");
149 static_assert(is_integral_v<_Nn>, "std::lcm arguments must be integers");
150 static_assert(_Mn(2) == 2, "std::lcm arguments must not be bool");
151 static_assert(_Nn(2) == 2, "std::lcm arguments must not be bool");
152 using _Up = make_unsigned_t<common_type_t<_Mn, _Nn>>;
153 return __detail::__lcm(__detail::__absu<_Up>(__m),
154 __detail::__absu<_Up>(__n));
159_GLIBCXX_END_NAMESPACE_VERSION
164#if __cplusplus > 201703L
167namespace std _GLIBCXX_VISIBILITY(default)
169_GLIBCXX_BEGIN_NAMESPACE_VERSION
171# define __cpp_lib_interpolate 201902L
173 template<typename _Tp>
175 enable_if_t<__and_v<is_arithmetic<_Tp>, is_same<remove_cv_t<_Tp>, _Tp>,
176 __not_<is_same<_Tp, bool>>>,
178 midpoint(_Tp __a, _Tp __b) noexcept
180 if constexpr (is_integral_v<_Tp>)
182 using _Up = make_unsigned_t<_Tp>;
193 return __a + __k * _Tp(_Up(__M - __m) / 2);
197 constexpr _Tp __lo = numeric_limits<_Tp>::min() * 2;
198 constexpr _Tp __hi = numeric_limits<_Tp>::max() / 2;
199 const _Tp __abs_a = __a < 0 ? -__a : __a;
200 const _Tp __abs_b = __b < 0 ? -__b : __b;
201 if (__abs_a <= __hi && __abs_b <= __hi) [[likely]]
202 return (__a + __b) / 2; // always correctly rounded
203 if (__abs_a < __lo) // not safe to halve __a
205 if (__abs_b < __lo) // not safe to halve __b
207 return __a/2 + __b/2; // otherwise correctly rounded
211 template<typename _Tp>
213 enable_if_t<__and_v<is_object<_Tp>, bool_constant<sizeof(_Tp) != 0>>, _Tp*>
214 midpoint(_Tp* __a, _Tp* __b) noexcept
216 return __a + (__b - __a) / 2;
218_GLIBCXX_END_NAMESPACE_VERSION
223#if __cplusplus > 201402L
224#include <bits/stl_function.h>
226namespace std _GLIBCXX_VISIBILITY(default)
228_GLIBCXX_BEGIN_NAMESPACE_VERSION
230 /// @addtogroup numeric_ops
233 /// @cond undocumented
234 template<typename _It, typename _Traits = iterator_traits<_It>,
235 typename _Cat = typename _Traits::iterator_category>
236 using __is_random_access_iter
237 = is_base_of<random_access_iterator_tag, _Cat>;
241 * @brief Calculate reduction of values in a range.
243 * @param __first Start of range.
244 * @param __last End of range.
245 * @param __init Starting value to add other values to.
246 * @param __binary_op A binary function object.
247 * @return The final sum.
249 * Reduce the values in the range `[first,last)` using a binary operation.
250 * The initial value is `init`. The values are not necessarily processed
253 * This algorithm is similar to `std::accumulate` but is not required to
254 * perform the operations in order from first to last. For operations
255 * that are commutative and associative the result will be the same as
256 * for `std::accumulate`, but for other operations (such as floating point
257 * arithmetic) the result can be different.
259 template<typename _InputIterator, typename _Tp, typename _BinaryOperation>
261 reduce(_InputIterator __first, _InputIterator __last, _Tp __init,
262 _BinaryOperation __binary_op)
264 using __ref = typename iterator_traits<_InputIterator>::reference;
265 static_assert(is_invocable_r_v<_Tp, _BinaryOperation&, _Tp&, __ref>);
266 static_assert(is_invocable_r_v<_Tp, _BinaryOperation&, __ref, _Tp&>);
267 static_assert(is_invocable_r_v<_Tp, _BinaryOperation&, _Tp&, _Tp&>);
268 static_assert(is_invocable_r_v<_Tp, _BinaryOperation&, __ref, __ref>);
269 if constexpr (__is_random_access_iter<_InputIterator>::value)
271 while ((__last - __first) >= 4)
273 _Tp __v1 = __binary_op(__first[0], __first[1]);
274 _Tp __v2 = __binary_op(__first[2], __first[3]);
275 _Tp __v3 = __binary_op(__v1, __v2);
276 __init = __binary_op(__init, __v3);
280 for (; __first != __last; ++__first)
281 __init = __binary_op(__init, *__first);
286 * @brief Calculate reduction of values in a range.
288 * @param __first Start of range.
289 * @param __last End of range.
290 * @param __init Starting value to add other values to.
291 * @return The final sum.
293 * Reduce the values in the range `[first,last)` using addition.
294 * Equivalent to calling `std::reduce(first, last, init, std::plus<>())`.
296 template<typename _InputIterator, typename _Tp>
298 reduce(_InputIterator __first, _InputIterator __last, _Tp __init)
299 { return std::reduce(__first, __last, std::move(__init), plus<>()); }
302 * @brief Calculate reduction of values in a range.
304 * @param __first Start of range.
305 * @param __last End of range.
306 * @return The final sum.
308 * Reduce the values in the range `[first,last)` using addition, with
309 * an initial value of `T{}`, where `T` is the iterator's value type.
310 * Equivalent to calling `std::reduce(first, last, T{}, std::plus<>())`.
312 template<typename _InputIterator>
313 inline typename iterator_traits<_InputIterator>::value_type
314 reduce(_InputIterator __first, _InputIterator __last)
316 using value_type = typename iterator_traits<_InputIterator>::value_type;
317 return std::reduce(__first, __last, value_type{}, plus<>());
321 * @brief Combine elements from two ranges and reduce
323 * @param __first1 Start of first range.
324 * @param __last1 End of first range.
325 * @param __first2 Start of second range.
326 * @param __init Starting value to add other values to.
327 * @param __binary_op1 The function used to perform reduction.
328 * @param __binary_op2 The function used to combine values from the ranges.
329 * @return The final sum.
331 * Call `binary_op2(first1[n],first2[n])` for each `n` in `[0,last1-first1)`
332 * and then use `binary_op1` to reduce the values returned by `binary_op2`
333 * to a single value of type `T`.
335 * The range beginning at `first2` must contain at least `last1-first1`
338 template<typename _InputIterator1, typename _InputIterator2, typename _Tp,
339 typename _BinaryOperation1, typename _BinaryOperation2>
341 transform_reduce(_InputIterator1 __first1, _InputIterator1 __last1,
342 _InputIterator2 __first2, _Tp __init,
343 _BinaryOperation1 __binary_op1,
344 _BinaryOperation2 __binary_op2)
346 if constexpr (__and_v<__is_random_access_iter<_InputIterator1>,
347 __is_random_access_iter<_InputIterator2>>)
349 while ((__last1 - __first1) >= 4)
351 _Tp __v1 = __binary_op1(__binary_op2(__first1[0], __first2[0]),
352 __binary_op2(__first1[1], __first2[1]));
353 _Tp __v2 = __binary_op1(__binary_op2(__first1[2], __first2[2]),
354 __binary_op2(__first1[3], __first2[3]));
355 _Tp __v3 = __binary_op1(__v1, __v2);
356 __init = __binary_op1(__init, __v3);
361 for (; __first1 != __last1; ++__first1, (void) ++__first2)
362 __init = __binary_op1(__init, __binary_op2(*__first1, *__first2));
367 * @brief Combine elements from two ranges and reduce
369 * @param __first1 Start of first range.
370 * @param __last1 End of first range.
371 * @param __first2 Start of second range.
372 * @param __init Starting value to add other values to.
373 * @return The final sum.
375 * Call `first1[n]*first2[n]` for each `n` in `[0,last1-first1)` and then
376 * use addition to sum those products to a single value of type `T`.
378 * The range beginning at `first2` must contain at least `last1-first1`
381 template<typename _InputIterator1, typename _InputIterator2, typename _Tp>
383 transform_reduce(_InputIterator1 __first1, _InputIterator1 __last1,
384 _InputIterator2 __first2, _Tp __init)
386 return std::transform_reduce(__first1, __last1, __first2,
388 plus<>(), multiplies<>());
392 * @brief Transform the elements of a range and reduce
394 * @param __first Start of range.
395 * @param __last End of range.
396 * @param __init Starting value to add other values to.
397 * @param __binary_op The function used to perform reduction.
398 * @param __unary_op The function used to transform values from the range.
399 * @return The final sum.
401 * Call `unary_op(first[n])` for each `n` in `[0,last-first)` and then
402 * use `binary_op` to reduce the values returned by `unary_op`
403 * to a single value of type `T`.
405 template<typename _InputIterator, typename _Tp,
406 typename _BinaryOperation, typename _UnaryOperation>
408 transform_reduce(_InputIterator __first, _InputIterator __last, _Tp __init,
409 _BinaryOperation __binary_op, _UnaryOperation __unary_op)
411 if constexpr (__is_random_access_iter<_InputIterator>::value)
413 while ((__last - __first) >= 4)
415 _Tp __v1 = __binary_op(__unary_op(__first[0]),
416 __unary_op(__first[1]));
417 _Tp __v2 = __binary_op(__unary_op(__first[2]),
418 __unary_op(__first[3]));
419 _Tp __v3 = __binary_op(__v1, __v2);
420 __init = __binary_op(__init, __v3);
424 for (; __first != __last; ++__first)
425 __init = __binary_op(__init, __unary_op(*__first));
429 /** @brief Output the cumulative sum of one range to a second range
431 * @param __first Start of input range.
432 * @param __last End of input range.
433 * @param __result Start of output range.
434 * @param __init Initial value.
435 * @param __binary_op Function to perform summation.
436 * @return The end of the output range.
438 * Write the cumulative sum (aka prefix sum, aka scan) of the input range
439 * to the output range. Each element of the output range contains the
440 * running total of all earlier elements (and the initial value),
441 * using `binary_op` for summation.
443 * This function generates an "exclusive" scan, meaning the Nth element
444 * of the output range is the sum of the first N-1 input elements,
445 * so the Nth input element is not included.
447 template<typename _InputIterator, typename _OutputIterator, typename _Tp,
448 typename _BinaryOperation>
450 exclusive_scan(_InputIterator __first, _InputIterator __last,
451 _OutputIterator __result, _Tp __init,
452 _BinaryOperation __binary_op)
454 while (__first != __last)
457 __init = __binary_op(__init, *__first);
459 *__result++ = std::move(__v);
464 /** @brief Output the cumulative sum of one range to a second range
466 * @param __first Start of input range.
467 * @param __last End of input range.
468 * @param __result Start of output range.
469 * @param __init Initial value.
470 * @return The end of the output range.
472 * Write the cumulative sum (aka prefix sum, aka scan) of the input range
473 * to the output range. Each element of the output range contains the
474 * running total of all earlier elements (and the initial value),
475 * using `std::plus<>` for summation.
477 * This function generates an "exclusive" scan, meaning the Nth element
478 * of the output range is the sum of the first N-1 input elements,
479 * so the Nth input element is not included.
481 template<typename _InputIterator, typename _OutputIterator, typename _Tp>
482 inline _OutputIterator
483 exclusive_scan(_InputIterator __first, _InputIterator __last,
484 _OutputIterator __result, _Tp __init)
486 return std::exclusive_scan(__first, __last, __result, std::move(__init),
490 /** @brief Output the cumulative sum of one range to a second range
492 * @param __first Start of input range.
493 * @param __last End of input range.
494 * @param __result Start of output range.
495 * @param __binary_op Function to perform summation.
496 * @param __init Initial value.
497 * @return The end of the output range.
499 * Write the cumulative sum (aka prefix sum, aka scan) of the input range
500 * to the output range. Each element of the output range contains the
501 * running total of all earlier elements (and the initial value),
502 * using `binary_op` for summation.
504 * This function generates an "inclusive" scan, meaning the Nth element
505 * of the output range is the sum of the first N input elements,
506 * so the Nth input element is included.
508 template<typename _InputIterator, typename _OutputIterator,
509 typename _BinaryOperation, typename _Tp>
511 inclusive_scan(_InputIterator __first, _InputIterator __last,
512 _OutputIterator __result, _BinaryOperation __binary_op,
515 for (; __first != __last; ++__first)
516 *__result++ = __init = __binary_op(__init, *__first);
520 /** @brief Output the cumulative sum of one range to a second range
522 * @param __first Start of input range.
523 * @param __last End of input range.
524 * @param __result Start of output range.
525 * @param __binary_op Function to perform summation.
526 * @return The end of the output range.
528 * Write the cumulative sum (aka prefix sum, aka scan) of the input range
529 * to the output range. Each element of the output range contains the
530 * running total of all earlier elements, using `binary_op` for summation.
532 * This function generates an "inclusive" scan, meaning the Nth element
533 * of the output range is the sum of the first N input elements,
534 * so the Nth input element is included.
536 template<typename _InputIterator, typename _OutputIterator,
537 typename _BinaryOperation>
539 inclusive_scan(_InputIterator __first, _InputIterator __last,
540 _OutputIterator __result, _BinaryOperation __binary_op)
542 if (__first != __last)
544 auto __init = *__first;
545 *__result++ = __init;
547 if (__first != __last)
548 __result = std::inclusive_scan(__first, __last, __result,
549 __binary_op, std::move(__init));
554 /** @brief Output the cumulative sum of one range to a second range
556 * @param __first Start of input range.
557 * @param __last End of input range.
558 * @param __result Start of output range.
559 * @return The end of the output range.
561 * Write the cumulative sum (aka prefix sum, aka scan) of the input range
562 * to the output range. Each element of the output range contains the
563 * running total of all earlier elements, using `std::plus<>` for summation.
565 * This function generates an "inclusive" scan, meaning the Nth element
566 * of the output range is the sum of the first N input elements,
567 * so the Nth input element is included.
569 template<typename _InputIterator, typename _OutputIterator>
570 inline _OutputIterator
571 inclusive_scan(_InputIterator __first, _InputIterator __last,
572 _OutputIterator __result)
573 { return std::inclusive_scan(__first, __last, __result, plus<>()); }
575 /** @brief Output the cumulative sum of one range to a second range
577 * @param __first Start of input range.
578 * @param __last End of input range.
579 * @param __result Start of output range.
580 * @param __init Initial value.
581 * @param __binary_op Function to perform summation.
582 * @param __unary_op Function to transform elements of the input range.
583 * @return The end of the output range.
585 * Write the cumulative sum (aka prefix sum, aka scan) of the input range
586 * to the output range. Each element of the output range contains the
587 * running total of all earlier elements (and the initial value),
588 * using `__unary_op` to transform the input elements
589 * and using `__binary_op` for summation.
591 * This function generates an "exclusive" scan, meaning the Nth element
592 * of the output range is the sum of the first N-1 input elements,
593 * so the Nth input element is not included.
595 template<typename _InputIterator, typename _OutputIterator, typename _Tp,
596 typename _BinaryOperation, typename _UnaryOperation>
598 transform_exclusive_scan(_InputIterator __first, _InputIterator __last,
599 _OutputIterator __result, _Tp __init,
600 _BinaryOperation __binary_op,
601 _UnaryOperation __unary_op)
603 while (__first != __last)
606 __init = __binary_op(__init, __unary_op(*__first));
608 *__result++ = std::move(__v);
613 /** @brief Output the cumulative sum of one range to a second range
615 * @param __first Start of input range.
616 * @param __last End of input range.
617 * @param __result Start of output range.
618 * @param __binary_op Function to perform summation.
619 * @param __unary_op Function to transform elements of the input range.
620 * @param __init Initial value.
621 * @return The end of the output range.
623 * Write the cumulative sum (aka prefix sum, aka scan) of the input range
624 * to the output range. Each element of the output range contains the
625 * running total of all earlier elements (and the initial value),
626 * using `__unary_op` to transform the input elements
627 * and using `__binary_op` for summation.
629 * This function generates an "inclusive" scan, meaning the Nth element
630 * of the output range is the sum of the first N input elements,
631 * so the Nth input element is included.
633 template<typename _InputIterator, typename _OutputIterator,
634 typename _BinaryOperation, typename _UnaryOperation, typename _Tp>
636 transform_inclusive_scan(_InputIterator __first, _InputIterator __last,
637 _OutputIterator __result,
638 _BinaryOperation __binary_op,
639 _UnaryOperation __unary_op,
642 for (; __first != __last; ++__first)
643 *__result++ = __init = __binary_op(__init, __unary_op(*__first));
647 /** @brief Output the cumulative sum of one range to a second range
649 * @param __first Start of input range.
650 * @param __last End of input range.
651 * @param __result Start of output range.
652 * @param __binary_op Function to perform summation.
653 * @param __unary_op Function to transform elements of the input range.
654 * @return The end of the output range.
656 * Write the cumulative sum (aka prefix sum, aka scan) of the input range
657 * to the output range. Each element of the output range contains the
658 * running total of all earlier elements,
659 * using `__unary_op` to transform the input elements
660 * and using `__binary_op` for summation.
662 * This function generates an "inclusive" scan, meaning the Nth element
663 * of the output range is the sum of the first N input elements,
664 * so the Nth input element is included.
666 template<typename _InputIterator, typename _OutputIterator,
667 typename _BinaryOperation, typename _UnaryOperation>
669 transform_inclusive_scan(_InputIterator __first, _InputIterator __last,
670 _OutputIterator __result,
671 _BinaryOperation __binary_op,
672 _UnaryOperation __unary_op)
674 if (__first != __last)
676 auto __init = __unary_op(*__first);
677 *__result++ = __init;
679 if (__first != __last)
680 __result = std::transform_inclusive_scan(__first, __last, __result,
681 __binary_op, __unary_op,
687 /// @} group numeric_ops
689_GLIBCXX_END_NAMESPACE_VERSION
692// Parallel STL algorithms
693# if __PSTL_EXECUTION_POLICIES_DEFINED
694// If <execution> has already been included, pull in implementations
695# include <pstl/glue_numeric_impl.h>
697// Otherwise just pull in forward declarations
698# include <pstl/glue_numeric_defs.h>
699# define __PSTL_NUMERIC_FORWARD_DECLARED 1
702// Feature test macro for parallel algorithms
703# define __cpp_lib_parallel_algorithm 201603L
706#endif /* _GLIBCXX_NUMERIC */