Prime factors
This commit is contained in:
29
futureskills/primefactors.cpp
Normal file
29
futureskills/primefactors.cpp
Normal file
@@ -0,0 +1,29 @@
|
||||
#include <cstdio>
|
||||
#include <cassert>
|
||||
#include <vector>
|
||||
|
||||
using prime_vec_t = std::vector<int>;
|
||||
|
||||
// https://en.wikipedia.org/wiki/Trial_division
|
||||
auto prime_factors(int num) -> prime_vec_t {
|
||||
prime_vec_t primes{};
|
||||
int f = 2;
|
||||
while (num > 1) {
|
||||
if (num % f == 0) {
|
||||
primes.emplace_back(f);
|
||||
num = num / f;
|
||||
} else {
|
||||
f += 1;
|
||||
}
|
||||
}
|
||||
return primes;
|
||||
}
|
||||
|
||||
auto main([[maybe_unused]]int argc, [[maybe_unused]]char const* argv[]) -> int {
|
||||
auto factors = prime_factors(20);
|
||||
for (auto const& factor : factors) {
|
||||
std::printf("%d, ", factor);
|
||||
}
|
||||
std::printf("\n");
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user