libstdc++
numeric
Go to the documentation of this file.
1// <numeric> -*- C++ -*-
2
3// Copyright (C) 2001-2026 Free Software Foundation, Inc.
4//
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)
9// any later version.
10
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.
15
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.
19
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/>.
24
25/*
26 *
27 * Copyright (c) 1994
28 * Hewlett-Packard Company
29 *
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.
37 *
38 *
39 * Copyright (c) 1996,1997
40 * Silicon Graphics Computer Systems, Inc.
41 *
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.
49 */
50
51/** @file include/numeric
52 * This is a Standard C++ Library header.
53 */
54
55#ifndef _GLIBCXX_NUMERIC
56#define _GLIBCXX_NUMERIC 1
57
58#ifdef _GLIBCXX_SYSHDR
59#pragma GCC system_header
60#endif
61
62#include <bits/c++config.h>
64#include <bits/stl_numeric.h>
65
66#ifdef _GLIBCXX_PARALLEL
67# include <parallel/numeric>
68#endif
69
70#if __cplusplus >= 201402L
71# include <type_traits>
72# include <bit>
73# include <ext/numeric_traits.h>
74#endif
75
76#if __cplusplus >= 201703L
77# include <bits/stl_function.h>
78#endif
79
80#if __cplusplus > 201703L
81# include <limits>
82#endif
83
84#define __glibcxx_want_algorithm_iterator_requirements
85#define __glibcxx_want_constexpr_numeric
86#define __glibcxx_want_gcd
87#define __glibcxx_want_gcd_lcm
88#define __glibcxx_want_interpolate
89#define __glibcxx_want_lcm
90#define __glibcxx_want_parallel_algorithm
91#define __glibcxx_want_ranges_iota
92#define __glibcxx_want_saturation_arithmetic
93#define __glibcxx_want_clmul
94#include <bits/version.h>
95
96#if __glibcxx_ranges_iota >= 202202L // C++ >= 23
97# include <bits/ranges_algobase.h> // for ranges::out_value_result
98#endif
99
100#ifdef __glibcxx_saturation_arithmetic // C++ >= 26
101# include <bits/sat_arith.h>
102#endif
103
104/**
105 * @defgroup numerics Numerics
106 *
107 * Components for performing numeric operations. Includes support for
108 * complex number types, random number generation, numeric (n-at-a-time)
109 * arrays, generalized numeric algorithms, and mathematical special functions.
110 */
111
112namespace std _GLIBCXX_VISIBILITY(default)
113{
114_GLIBCXX_BEGIN_NAMESPACE_VERSION
115
116#if __cplusplus >= 201402L
117namespace __detail
118{
119 // Like std::abs, but supports unsigned types and returns the specified type,
120 // so |std::numeric_limits<_Tp>::min()| is OK if representable in _Res.
121 template<typename _Res, typename _Tp>
122 constexpr _Res
123 __abs_r(_Tp __val)
124 {
125 static_assert(sizeof(_Res) >= sizeof(_Tp),
126 "result type must be at least as wide as the input type");
127
128 if (__val >= 0)
129 return __val;
130#ifdef _GLIBCXX_ASSERTIONS
131 if (!__is_constant_evaluated()) // overflow already detected in constexpr
132 __glibcxx_assert(__val != __gnu_cxx::__int_traits<_Res>::__min);
133#endif
134 return -static_cast<_Res>(__val);
135 }
136
137 template<typename> void __abs_r(bool) = delete;
138
139 // GCD implementation, using Stein's algorithm
140 template<typename _Tp>
141 constexpr _Tp
142 __gcd(_Tp __m, _Tp __n)
143 {
144 static_assert(is_unsigned<_Tp>::value, "type must be unsigned");
145
146 if (__m == 0)
147 return __n;
148 if (__n == 0)
149 return __m;
150
151 const int __i = std::__countr_zero(__m);
152 __m >>= __i;
153 const int __j = std::__countr_zero(__n);
154 __n >>= __j;
155 const int __k = __i < __j ? __i : __j; // min(i, j)
156
157 while (true)
158 {
159 if (__m > __n)
160 {
161 _Tp __tmp = __m;
162 __m = __n;
163 __n = __tmp;
164 }
165
166 __n -= __m;
167
168 if (__n == 0)
169 return __m << __k;
170
171 __n >>= std::__countr_zero(__n);
172 }
173 }
174} // namespace __detail
175#endif // C++14
176
177#ifdef __cpp_lib_gcd_lcm // C++ >= 17
178 /// Greatest common divisor
179 template<typename _Mn, typename _Nn>
181 gcd(_Mn __m, _Nn __n) noexcept
182 {
183 static_assert(is_integral_v<_Mn> && is_integral_v<_Nn>,
184 "std::gcd arguments must be integers");
185 static_assert(_Mn(2) == 2 && _Nn(2) == 2,
186 "std::gcd arguments must not be bool");
187 using _Ct = common_type_t<_Mn, _Nn>;
188 const _Ct __m2 = __detail::__abs_r<_Ct>(__m);
189 const _Ct __n2 = __detail::__abs_r<_Ct>(__n);
190 return __detail::__gcd<make_unsigned_t<_Ct>>(__m2, __n2);
191 }
192
193 /// Least common multiple
194 template<typename _Mn, typename _Nn>
196 lcm(_Mn __m, _Nn __n) noexcept
197 {
198 static_assert(is_integral_v<_Mn> && is_integral_v<_Nn>,
199 "std::lcm arguments must be integers");
200 static_assert(_Mn(2) == 2 && _Nn(2) == 2,
201 "std::lcm arguments must not be bool");
202 using _Ct = common_type_t<_Mn, _Nn>;
203 const _Ct __m2 = __detail::__abs_r<_Ct>(__m);
204 const _Ct __n2 = __detail::__abs_r<_Ct>(__n);
205 if (__m2 == 0 || __n2 == 0)
206 return 0;
207 _Ct __r = __m2 / __detail::__gcd<make_unsigned_t<_Ct>>(__m2, __n2);
208
209 if constexpr (is_signed_v<_Ct>)
210 if (__is_constant_evaluated())
211 return __r * __n2; // constant evaluation can detect overflow here.
212
213 bool __overflow = __builtin_mul_overflow(__r, __n2, &__r);
214 __glibcxx_assert(!__overflow);
215 return __r;
216 }
217
218#endif // __cpp_lib_gcd_lcm
219
220 // midpoint
221#ifdef __cpp_lib_interpolate // C++ >= 20
222 template<typename _Tp>
223 constexpr
225 __not_<is_same<_Tp, bool>>>,
226 _Tp>
227 midpoint(_Tp __a, _Tp __b) noexcept
228 {
229 if constexpr (is_integral_v<_Tp>)
230 {
231 using _Up = make_unsigned_t<_Tp>;
232
233 int __k = 1;
234 _Up __m = __a;
235 _Up __M = __b;
236 if (__a > __b)
237 {
238 __k = -1;
239 __m = __b;
240 __M = __a;
241 }
242 return __a + __k * _Tp(_Up(__M - __m) / 2);
243 }
244 else // is_floating
245 {
246 constexpr _Tp __lo = numeric_limits<_Tp>::min() * 2;
247 constexpr _Tp __hi = numeric_limits<_Tp>::max() / 2;
248 const _Tp __abs_a = __a < 0 ? -__a : __a;
249 const _Tp __abs_b = __b < 0 ? -__b : __b;
250 if (__abs_a <= __hi && __abs_b <= __hi) [[likely]]
251 return (__a + __b) / 2; // always correctly rounded
252 if (__abs_a < __lo) // not safe to halve __a
253 return __a + __b/2;
254 if (__abs_b < __lo) // not safe to halve __b
255 return __a/2 + __b;
256 return __a/2 + __b/2; // otherwise correctly rounded
257 }
258 }
259
260 template<typename _Tp>
261 constexpr enable_if_t<is_object_v<_Tp>, _Tp*>
262 midpoint(_Tp* __a, _Tp* __b) noexcept
263 {
264 static_assert( sizeof(_Tp) != 0, "type must be complete" );
265 return __a + (__b - __a) / 2;
266 }
267#endif // __cpp_lib_interpolate
268
269#if __cplusplus >= 201703L // __cpp_lib_parallel_algorithm but not hosted-only
270 /// @addtogroup numeric_ops
271 /// @{
272
273 /**
274 * @brief Calculate reduction of values in a range.
275 *
276 * @param __first Start of range.
277 * @param __last End of range.
278 * @param __init Starting value to add other values to.
279 * @param __binary_op A binary function object.
280 * @return The final sum.
281 *
282 * Reduce the values in the range `[first,last)` using a binary operation.
283 * The initial value is `init`. The values are not necessarily processed
284 * in order.
285 *
286 * This algorithm is similar to `std::accumulate` but is not required to
287 * perform the operations in order from first to last. For operations
288 * that are commutative and associative the result will be the same as
289 * for `std::accumulate`, but for other operations (such as floating point
290 * arithmetic) the result can be different.
291 */
292 template<typename _InputIterator, typename _Tp, typename _BinaryOperation>
293 _GLIBCXX20_CONSTEXPR
294 _Tp
295 reduce(_InputIterator __first, _InputIterator __last, _Tp __init,
296 _BinaryOperation __binary_op)
297 {
298 using __ref = typename iterator_traits<_InputIterator>::reference;
299 static_assert(is_invocable_r_v<_Tp, _BinaryOperation&, _Tp&, __ref>);
300 static_assert(is_invocable_r_v<_Tp, _BinaryOperation&, __ref, _Tp&>);
301 static_assert(is_invocable_r_v<_Tp, _BinaryOperation&, _Tp&, _Tp&>);
302 static_assert(is_invocable_r_v<_Tp, _BinaryOperation&, __ref, __ref>);
303 if constexpr (__is_any_random_access_iter<_InputIterator>::value)
304 {
305 while ((__last - __first) >= 4)
306 {
307 _Tp __v1 = __binary_op(__first[0], __first[1]);
308 _Tp __v2 = __binary_op(__first[2], __first[3]);
309 _Tp __v3 = __binary_op(__v1, __v2);
310 __init = __binary_op(__init, __v3);
311 __first += 4;
312 }
313 }
314 for (; __first != __last; ++__first)
315 __init = __binary_op(__init, *__first);
316 return __init;
317 }
318
319 /**
320 * @brief Calculate reduction of values in a range.
321 *
322 * @param __first Start of range.
323 * @param __last End of range.
324 * @param __init Starting value to add other values to.
325 * @return The final sum.
326 *
327 * Reduce the values in the range `[first,last)` using addition.
328 * Equivalent to calling `std::reduce(first, last, init, std::plus<>())`.
329 */
330 template<typename _InputIterator, typename _Tp>
331 _GLIBCXX20_CONSTEXPR
332 inline _Tp
333 reduce(_InputIterator __first, _InputIterator __last, _Tp __init)
334 { return std::reduce(__first, __last, std::move(__init), plus<>()); }
335
336 /**
337 * @brief Calculate reduction of values in a range.
338 *
339 * @param __first Start of range.
340 * @param __last End of range.
341 * @return The final sum.
342 *
343 * Reduce the values in the range `[first,last)` using addition, with
344 * an initial value of `T{}`, where `T` is the iterator's value type.
345 * Equivalent to calling `std::reduce(first, last, T{}, std::plus<>())`.
346 */
347 template<typename _InputIterator>
348 _GLIBCXX20_CONSTEXPR
349 inline typename iterator_traits<_InputIterator>::value_type
350 reduce(_InputIterator __first, _InputIterator __last)
351 {
353 return std::reduce(__first, __last, value_type{}, plus<>());
354 }
355
356 /**
357 * @brief Combine elements from two ranges and reduce
358 *
359 * @param __first1 Start of first range.
360 * @param __last1 End of first range.
361 * @param __first2 Start of second range.
362 * @param __init Starting value to add other values to.
363 * @param __binary_op1 The function used to perform reduction.
364 * @param __binary_op2 The function used to combine values from the ranges.
365 * @return The final sum.
366 *
367 * Call `binary_op2(first1[n],first2[n])` for each `n` in `[0,last1-first1)`
368 * and then use `binary_op1` to reduce the values returned by `binary_op2`
369 * to a single value of type `T`.
370 *
371 * The range beginning at `first2` must contain at least `last1-first1`
372 * elements.
373 */
374 template<typename _InputIterator1, typename _InputIterator2, typename _Tp,
375 typename _BinaryOperation1, typename _BinaryOperation2>
376 _GLIBCXX20_CONSTEXPR
377 _Tp
378 transform_reduce(_InputIterator1 __first1, _InputIterator1 __last1,
379 _InputIterator2 __first2, _Tp __init,
380 _BinaryOperation1 __binary_op1,
381 _BinaryOperation2 __binary_op2)
382 {
383 if constexpr (__and_v<__is_any_random_access_iter<_InputIterator1>,
384 __is_any_random_access_iter<_InputIterator2>>)
385 {
386 while ((__last1 - __first1) >= 4)
387 {
388 _Tp __v1 = __binary_op1(__binary_op2(__first1[0], __first2[0]),
389 __binary_op2(__first1[1], __first2[1]));
390 _Tp __v2 = __binary_op1(__binary_op2(__first1[2], __first2[2]),
391 __binary_op2(__first1[3], __first2[3]));
392 _Tp __v3 = __binary_op1(__v1, __v2);
393 __init = __binary_op1(__init, __v3);
394 __first1 += 4;
395 __first2 += 4;
396 }
397 }
398 for (; __first1 != __last1; ++__first1, (void) ++__first2)
399 __init = __binary_op1(__init, __binary_op2(*__first1, *__first2));
400 return __init;
401 }
402
403 /**
404 * @brief Combine elements from two ranges and reduce
405 *
406 * @param __first1 Start of first range.
407 * @param __last1 End of first range.
408 * @param __first2 Start of second range.
409 * @param __init Starting value to add other values to.
410 * @return The final sum.
411 *
412 * Call `first1[n]*first2[n]` for each `n` in `[0,last1-first1)` and then
413 * use addition to sum those products to a single value of type `T`.
414 *
415 * The range beginning at `first2` must contain at least `last1-first1`
416 * elements.
417 */
418 template<typename _InputIterator1, typename _InputIterator2, typename _Tp>
419 _GLIBCXX20_CONSTEXPR
420 inline _Tp
421 transform_reduce(_InputIterator1 __first1, _InputIterator1 __last1,
422 _InputIterator2 __first2, _Tp __init)
423 {
424 return std::transform_reduce(__first1, __last1, __first2,
425 std::move(__init),
426 plus<>(), multiplies<>());
427 }
428
429 /**
430 * @brief Transform the elements of a range and reduce
431 *
432 * @param __first Start of range.
433 * @param __last End of range.
434 * @param __init Starting value to add other values to.
435 * @param __binary_op The function used to perform reduction.
436 * @param __unary_op The function used to transform values from the range.
437 * @return The final sum.
438 *
439 * Call `unary_op(first[n])` for each `n` in `[0,last-first)` and then
440 * use `binary_op` to reduce the values returned by `unary_op`
441 * to a single value of type `T`.
442 */
443 template<typename _InputIterator, typename _Tp,
444 typename _BinaryOperation, typename _UnaryOperation>
445 _GLIBCXX20_CONSTEXPR
446 _Tp
447 transform_reduce(_InputIterator __first, _InputIterator __last, _Tp __init,
448 _BinaryOperation __binary_op, _UnaryOperation __unary_op)
449 {
450 if constexpr (__is_any_random_access_iter<_InputIterator>::value)
451 {
452 while ((__last - __first) >= 4)
453 {
454 _Tp __v1 = __binary_op(__unary_op(__first[0]),
455 __unary_op(__first[1]));
456 _Tp __v2 = __binary_op(__unary_op(__first[2]),
457 __unary_op(__first[3]));
458 _Tp __v3 = __binary_op(__v1, __v2);
459 __init = __binary_op(__init, __v3);
460 __first += 4;
461 }
462 }
463 for (; __first != __last; ++__first)
464 __init = __binary_op(__init, __unary_op(*__first));
465 return __init;
466 }
467
468 /** @brief Output the cumulative sum of one range to a second range
469 *
470 * @param __first Start of input range.
471 * @param __last End of input range.
472 * @param __result Start of output range.
473 * @param __init Initial value.
474 * @param __binary_op Function to perform summation.
475 * @return The end of the output range.
476 *
477 * Write the cumulative sum (aka prefix sum, aka scan) of the input range
478 * to the output range. Each element of the output range contains the
479 * running total of all earlier elements (and the initial value),
480 * using `binary_op` for summation.
481 *
482 * This function generates an "exclusive" scan, meaning the Nth element
483 * of the output range is the sum of the first N-1 input elements,
484 * so the Nth input element is not included.
485 */
486 template<typename _InputIterator, typename _OutputIterator, typename _Tp,
487 typename _BinaryOperation>
488 _GLIBCXX20_CONSTEXPR
489 _OutputIterator
490 exclusive_scan(_InputIterator __first, _InputIterator __last,
491 _OutputIterator __result, _Tp __init,
492 _BinaryOperation __binary_op)
493 {
494 while (__first != __last)
495 {
496 _Tp __v = std::move(__init);
497 __init = __binary_op(__v, *__first);
498 ++__first;
499 *__result++ = std::move(__v);
500 }
501 return __result;
502 }
503
504 /** @brief Output the cumulative sum of one range to a second range
505 *
506 * @param __first Start of input range.
507 * @param __last End of input range.
508 * @param __result Start of output range.
509 * @param __init Initial value.
510 * @return The end of the output range.
511 *
512 * Write the cumulative sum (aka prefix sum, aka scan) of the input range
513 * to the output range. Each element of the output range contains the
514 * running total of all earlier elements (and the initial value),
515 * using `std::plus<>` for summation.
516 *
517 * This function generates an "exclusive" scan, meaning the Nth element
518 * of the output range is the sum of the first N-1 input elements,
519 * so the Nth input element is not included.
520 */
521 template<typename _InputIterator, typename _OutputIterator, typename _Tp>
522 _GLIBCXX20_CONSTEXPR
523 inline _OutputIterator
524 exclusive_scan(_InputIterator __first, _InputIterator __last,
525 _OutputIterator __result, _Tp __init)
526 {
527 return std::exclusive_scan(__first, __last, __result, std::move(__init),
528 plus<>());
529 }
530
531 /** @brief Output the cumulative sum of one range to a second range
532 *
533 * @param __first Start of input range.
534 * @param __last End of input range.
535 * @param __result Start of output range.
536 * @param __binary_op Function to perform summation.
537 * @param __init Initial value.
538 * @return The end of the output range.
539 *
540 * Write the cumulative sum (aka prefix sum, aka scan) of the input range
541 * to the output range. Each element of the output range contains the
542 * running total of all earlier elements (and the initial value),
543 * using `binary_op` for summation.
544 *
545 * This function generates an "inclusive" scan, meaning the Nth element
546 * of the output range is the sum of the first N input elements,
547 * so the Nth input element is included.
548 */
549 template<typename _InputIterator, typename _OutputIterator,
550 typename _BinaryOperation, typename _Tp>
551 _GLIBCXX20_CONSTEXPR
552 _OutputIterator
553 inclusive_scan(_InputIterator __first, _InputIterator __last,
554 _OutputIterator __result, _BinaryOperation __binary_op,
555 _Tp __init)
556 {
557 for (; __first != __last; ++__first)
558 *__result++ = __init = __binary_op(__init, *__first);
559 return __result;
560 }
561
562 /** @brief Output the cumulative sum of one range to a second range
563 *
564 * @param __first Start of input range.
565 * @param __last End of input range.
566 * @param __result Start of output range.
567 * @param __binary_op Function to perform summation.
568 * @return The end of the output range.
569 *
570 * Write the cumulative sum (aka prefix sum, aka scan) of the input range
571 * to the output range. Each element of the output range contains the
572 * running total of all earlier elements, using `binary_op` for summation.
573 *
574 * This function generates an "inclusive" scan, meaning the Nth element
575 * of the output range is the sum of the first N input elements,
576 * so the Nth input element is included.
577 */
578 template<typename _InputIterator, typename _OutputIterator,
579 typename _BinaryOperation>
580 _GLIBCXX20_CONSTEXPR
581 _OutputIterator
582 inclusive_scan(_InputIterator __first, _InputIterator __last,
583 _OutputIterator __result, _BinaryOperation __binary_op)
584 {
585 if (__first != __last)
586 {
587 auto __init = _GLIBCXX_ITER_MOVE(__first);
588 *__result++ = __init;
589 ++__first;
590 if (__first != __last)
591 __result = std::inclusive_scan(__first, __last, __result,
592 __binary_op, std::move(__init));
593 }
594 return __result;
595 }
596
597 /** @brief Output the cumulative sum of one range to a second range
598 *
599 * @param __first Start of input range.
600 * @param __last End of input range.
601 * @param __result Start of output range.
602 * @return The end of the output range.
603 *
604 * Write the cumulative sum (aka prefix sum, aka scan) of the input range
605 * to the output range. Each element of the output range contains the
606 * running total of all earlier elements, using `std::plus<>` for summation.
607 *
608 * This function generates an "inclusive" scan, meaning the Nth element
609 * of the output range is the sum of the first N input elements,
610 * so the Nth input element is included.
611 */
612 template<typename _InputIterator, typename _OutputIterator>
613 _GLIBCXX20_CONSTEXPR
614 inline _OutputIterator
615 inclusive_scan(_InputIterator __first, _InputIterator __last,
616 _OutputIterator __result)
617 { return std::inclusive_scan(__first, __last, __result, plus<>()); }
618
619 /** @brief Output the cumulative sum of one range to a second range
620 *
621 * @param __first Start of input range.
622 * @param __last End of input range.
623 * @param __result Start of output range.
624 * @param __init Initial value.
625 * @param __binary_op Function to perform summation.
626 * @param __unary_op Function to transform elements of the input range.
627 * @return The end of the output range.
628 *
629 * Write the cumulative sum (aka prefix sum, aka scan) of the input range
630 * to the output range. Each element of the output range contains the
631 * running total of all earlier elements (and the initial value),
632 * using `__unary_op` to transform the input elements
633 * and using `__binary_op` for summation.
634 *
635 * This function generates an "exclusive" scan, meaning the Nth element
636 * of the output range is the sum of the first N-1 input elements,
637 * so the Nth input element is not included.
638 */
639 template<typename _InputIterator, typename _OutputIterator, typename _Tp,
640 typename _BinaryOperation, typename _UnaryOperation>
641 _GLIBCXX20_CONSTEXPR
642 _OutputIterator
643 transform_exclusive_scan(_InputIterator __first, _InputIterator __last,
644 _OutputIterator __result, _Tp __init,
645 _BinaryOperation __binary_op,
646 _UnaryOperation __unary_op)
647 {
648 while (__first != __last)
649 {
650 auto __v = std::move(__init);
651 __init = __binary_op(__v, __unary_op(*__first));
652 ++__first;
653 *__result++ = std::move(__v);
654 }
655 return __result;
656 }
657
658 /** @brief Output the cumulative sum of one range to a second range
659 *
660 * @param __first Start of input range.
661 * @param __last End of input range.
662 * @param __result Start of output range.
663 * @param __binary_op Function to perform summation.
664 * @param __unary_op Function to transform elements of the input range.
665 * @param __init Initial value.
666 * @return The end of the output range.
667 *
668 * Write the cumulative sum (aka prefix sum, aka scan) of the input range
669 * to the output range. Each element of the output range contains the
670 * running total of all earlier elements (and the initial value),
671 * using `__unary_op` to transform the input elements
672 * and using `__binary_op` for summation.
673 *
674 * This function generates an "inclusive" scan, meaning the Nth element
675 * of the output range is the sum of the first N input elements,
676 * so the Nth input element is included.
677 */
678 template<typename _InputIterator, typename _OutputIterator,
679 typename _BinaryOperation, typename _UnaryOperation, typename _Tp>
680 _GLIBCXX20_CONSTEXPR
681 _OutputIterator
682 transform_inclusive_scan(_InputIterator __first, _InputIterator __last,
683 _OutputIterator __result,
684 _BinaryOperation __binary_op,
685 _UnaryOperation __unary_op,
686 _Tp __init)
687 {
688 for (; __first != __last; ++__first)
689 *__result++ = __init = __binary_op(__init, __unary_op(*__first));
690 return __result;
691 }
692
693 /** @brief Output the cumulative sum of one range to a second range
694 *
695 * @param __first Start of input range.
696 * @param __last End of input range.
697 * @param __result Start of output range.
698 * @param __binary_op Function to perform summation.
699 * @param __unary_op Function to transform elements of the input range.
700 * @return The end of the output range.
701 *
702 * Write the cumulative sum (aka prefix sum, aka scan) of the input range
703 * to the output range. Each element of the output range contains the
704 * running total of all earlier elements,
705 * using `__unary_op` to transform the input elements
706 * and using `__binary_op` for summation.
707 *
708 * This function generates an "inclusive" scan, meaning the Nth element
709 * of the output range is the sum of the first N input elements,
710 * so the Nth input element is included.
711 */
712 template<typename _InputIterator, typename _OutputIterator,
713 typename _BinaryOperation, typename _UnaryOperation>
714 _GLIBCXX20_CONSTEXPR
715 _OutputIterator
716 transform_inclusive_scan(_InputIterator __first, _InputIterator __last,
717 _OutputIterator __result,
718 _BinaryOperation __binary_op,
719 _UnaryOperation __unary_op)
720 {
721 if (__first != __last)
722 {
723 auto __init = __unary_op(*__first);
724 *__result++ = __init;
725 ++__first;
726 if (__first != __last)
727 __result = std::transform_inclusive_scan(__first, __last, __result,
728 __binary_op, __unary_op,
729 std::move(__init));
730 }
731 return __result;
732 }
733
734 /// @} group numeric_ops
735#endif // C++17
736
737#if __glibcxx_ranges_iota >= 202202L // C++ >= 23
738namespace ranges
739{
740 template<typename _Out, typename _Tp>
741 using iota_result = out_value_result<_Out, _Tp>;
742
743 struct __iota_fn
744 {
745 template<input_or_output_iterator _Out, sentinel_for<_Out> _Sent, weakly_incrementable _Tp>
746 requires indirectly_writable<_Out, const _Tp&>
747 constexpr iota_result<_Out, _Tp>
748 operator()(_Out __first, _Sent __last, _Tp __value) const
749 {
750 while (__first != __last)
751 {
752 *__first = static_cast<const _Tp&>(__value);
753 ++__first;
754 ++__value;
755 }
756 return {std::move(__first), std::move(__value)};
757 }
758
759 template<weakly_incrementable _Tp, output_range<const _Tp&> _Range>
760 constexpr iota_result<borrowed_iterator_t<_Range>, _Tp>
761 operator()(_Range&& __r, _Tp __value) const
762 { return (*this)(ranges::begin(__r), ranges::end(__r), std::move(__value)); }
763 };
764
765 inline constexpr __iota_fn iota{};
766} // namespace ranges
767#endif // __glibcxx_ranges_iota
768
769#ifdef __glibcxx_clmul // C++29
770 template<typename _Tp>
771 class wide_result {
772 public:
773 static_assert(__is_unsigned_integer<_Tp>::value);
774 constexpr _Tp high() const noexcept { return _M_high; }
775 constexpr _Tp low() const noexcept { return _M_low; }
776
777 friend constexpr bool operator==(const wide_result&,
778 const wide_result&) = default;
779#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
780 constexpr wide_result(_Tp __high, _Tp __low) noexcept
781 : _M_low(__low), _M_high(__high) {}
782 friend constexpr strong_ordering operator<=>(const wide_result& __x,
783 const wide_result& __y)
784 noexcept
785 {
786 if (auto __r = __x._M_high <=> __y._M_high; __r != 0)
787 return __r;
788 return __x._M_low <=> __y._M_low;
789 }
790 private:
791 _Tp _M_low, _M_high;
792#else
793 constexpr wide_result(_Tp __high, _Tp __low) noexcept
794 : _M_high(__high), _M_low(__low) {}
795 friend constexpr strong_ordering operator<=>(const wide_result& __x,
796 const wide_result& __y)
797 noexcept = default;
798 private:
799 _Tp _M_high, _M_low;
800#endif
801 };
802
803 template<__unsigned_integer _Tp>
804 [[nodiscard]] constexpr wide_result<_Tp>
805 widening_clmul(_Tp __x, _Tp __y) noexcept
806 {
807 _Tp __high, __low;
808#if _GLIBCXX_USE_BUILTIN_TRAIT(__builtin_clmulg)
809 __low = __builtin_clmulg(__x, __y, &__high);
810 return wide_result<_Tp>(__high, __low);
811#elif _GLIBCXX_USE_BUILTIN_TRAIT(__builtin_elementwise_clmul) \
812 && _GLIBCXX_USE_BUILTIN_TRAIT(__builtin_bitreverseg)
813 __low = __builtin_elementwise_clmul(__x, __y);
814 __high = __builtin_elementwise_clmul(__builtin_bitreverseg(__x),
815 __builtin_bitreverseg(__y));
816 return wide_result<_Tp>(__builtin_bitreverseg(__high) >> 1, __low);
817#else
818 constexpr auto _Nd = __gnu_cxx::__int_traits<_Tp>::__digits;
819 __high = 0;
820 __low = (__y & _Tp(1)) ? __x : 0;
821 for (int __i = 1; __i < _Nd; ++__i)
822 if ((__y >> __i) & _Tp(1))
823 {
824 __low ^= __x << __i;
825 __high ^= __x >> (_Nd - __i);
826 }
827 return wide_result<_Tp>(__high, __low);
828#endif
829 }
830
831 template<__unsigned_integer _Tp>
832 [[nodiscard]] constexpr _Tp
833 clmul(_Tp __x, _Tp __y) noexcept
834 {
835#if _GLIBCXX_USE_BUILTIN_TRAIT(__builtin_clmulg)
836 return __builtin_clmulg(__x, __y);
837#elif _GLIBCXX_USE_BUILTIN_TRAIT(__builtin_elementwise_clmul)
838 return __builtin_elementwise_clmul(__x, __y);
839#else
840 _Tp __res = 0;
841 constexpr auto _Nd = __gnu_cxx::__int_traits<_Tp>::__digits;
842 for (int __i = 0; __i < _Nd; ++__i)
843 if ((__y >> __i) & _Tp(1))
844 __res ^= __x << __i;
845 return __res;
846#endif
847 }
848#endif // C++29
849
850_GLIBCXX_END_NAMESPACE_VERSION
851} // namespace std
852
853#if __cpp_lib_parallel_algorithm // C++ >= 17 && HOSTED
854// Parallel STL algorithms
855# if _PSTL_EXECUTION_POLICIES_DEFINED
856// If <execution> has already been included, pull in implementations
857# include <pstl/glue_numeric_impl.h>
858# else
859// Otherwise just pull in forward declarations
860# include <pstl/glue_numeric_defs.h>
861# define _PSTL_NUMERIC_FORWARD_DECLARED 1
862# endif
863#endif // __cpp_lib_parallel_algorithm
864
865#endif /* _GLIBCXX_NUMERIC */
typename common_type< _Tp... >::type common_type_t
Alias template for common_type.
Definition type_traits:2979
typename make_unsigned< _Tp >::type make_unsigned_t
Alias template for make_unsigned.
Definition type_traits:2275
typename enable_if< _Cond, _Tp >::type enable_if_t
Alias template for enable_if.
Definition type_traits:2971
constexpr std::remove_reference< _Tp >::type && move(_Tp &&__t) noexcept
Convert a value to an rvalue.
Definition move.h:138
constexpr _OutputIterator inclusive_scan(_InputIterator __first, _InputIterator __last, _OutputIterator __result, _BinaryOperation __binary_op, _Tp __init)
Output the cumulative sum of one range to a second range.
Definition numeric:553
constexpr _OutputIterator exclusive_scan(_InputIterator __first, _InputIterator __last, _OutputIterator __result, _Tp __init, _BinaryOperation __binary_op)
Output the cumulative sum of one range to a second range.
Definition numeric:490
constexpr _OutputIterator transform_inclusive_scan(_InputIterator __first, _InputIterator __last, _OutputIterator __result, _BinaryOperation __binary_op, _UnaryOperation __unary_op, _Tp __init)
Output the cumulative sum of one range to a second range.
Definition numeric:682
constexpr _OutputIterator transform_exclusive_scan(_InputIterator __first, _InputIterator __last, _OutputIterator __result, _Tp __init, _BinaryOperation __binary_op, _UnaryOperation __unary_op)
Output the cumulative sum of one range to a second range.
Definition numeric:643
constexpr _Tp transform_reduce(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _Tp __init, _BinaryOperation1 __binary_op1, _BinaryOperation2 __binary_op2)
Combine elements from two ranges and reduce.
Definition numeric:378
constexpr _Tp reduce(_InputIterator __first, _InputIterator __last, _Tp __init, _BinaryOperation __binary_op)
Calculate reduction of values in a range.
Definition numeric:295
ISO C++ entities toplevel namespace is std.
Implementation details not part of the namespace std interface.
constexpr common_type_t< _Mn, _Nn > lcm(_Mn __m, _Nn __n)
Least common multiple.
constexpr common_type_t< _Mn, _Nn > gcd(_Mn __m, _Nn __n) noexcept
Greatest common divisor.
static constexpr _Tp max() noexcept
Definition limits:336
static constexpr _Tp min() noexcept
Definition limits:332
Traits class for iterators.
One of the math functors.
One of the math functors.
Parallel STL function calls corresponding to stl_numeric.h. The functions defined here mainly do case...