carl  24.04
Computer ARithmetic Library
FactorizationFactory.h
Go to the documentation of this file.
1 #pragma once
2 
3 #include "PrimeFactory.h"
4 
5 #include <optional>
6 
7 #include <vector>
8 
9 namespace carl {
10 
11 /**
12  * This class provides a cached factorization for numbers.
13  */
14 template<typename T>
16 
17 /**
18  * This class provides a cached prime factorization for std::size_t.
19  * Factorizations contain all prime factors, including multiples.
20  * Additionally, we define:
21  * - factorization(0) = {}
22  * - factorization(1) = {1}
23  */
24 template<>
26 private:
28  std::vector<std::optional<std::vector<uint>>> mCache;
29 public:
31  mCache.emplace_back(std::vector<uint>({}));
32  mCache.emplace_back(std::vector<uint>({1}));
33  }
34  /// Returns the factorization of n.
35  const std::vector<uint>& operator()(uint n) {
36  while (mCache.size() <= n) {
37  mCache.emplace_back();
38  }
39  if (mCache[n]) {
40  return *mCache[n];
41  }
42  assert(n >= 2);
43  mCache[n] = std::vector<uint>();
44  uint cur = n;
45  for (std::size_t i = 0; ;) {
46  if (cur % mPrimes[i] == 0) {
47  mCache[n]->push_back(mPrimes[i]);
48  cur /= mPrimes[i];
49  } else {
50  i++;
51  }
52  if (cur == 1) break;
53  }
54  return *mCache[n];
55  }
56 
57 };
58 
59 }
carl is the main namespace for the library.
std::uint64_t uint
Definition: numbers.h:16
This class provides a cached factorization for numbers.
std::vector< std::optional< std::vector< uint > > > mCache
const std::vector< uint > & operator()(uint n)
Returns the factorization of n.