prime_factors.h
Go to the documentation of this file.
1 /*
2 This file is part of the Ristra Wonton project.
3 Please see the license file at the root of this repository, or at:
4  https://github.com/laristra/wonton/blob/master/LICENSE
5 */
6 
7 #ifndef WONTON_PRIME_FACTOR_H_
8 #define WONTON_PRIME_FACTOR_H_
9 
10 namespace Wonton {
11 
18 static
19 std::vector<int> prime_factors(unsigned int const N) {
20  constexpr int nprimes = 10;
21  int primes[nprimes] = {2,3,5,7,11,13,17,19,23,29}; // unlikely to need more
22  std::vector<int> factors;
23 
24  switch (N) {
25  case 0: case 1:
26  break;
27  case 2: case 3:
28  factors.push_back(N);
29  break;
30  default: {
31  int num = N;
32  int i = 0;
33  bool done = false;
34  while (!done) {
35  if (num%primes[i] == 0) {
36  factors.push_back(primes[i]);
37  num = num/primes[i];
38  } else
39  i = i+1;
40  if (num == 1 || i == nprimes)
41  done = true;
42  }
43  break;
44  }
45  }
46 
47  return factors;
48 }
49 
50 } // end namespace Wonton
51 
52 #endif
Factorize a number N into D equal (or nearly equal) factors.
Definition: adaptive_refinement_mesh.h:31