Prime factors
This commit is contained in:
41
.gitignore
vendored
Normal file
41
.gitignore
vendored
Normal file
@@ -0,0 +1,41 @@
|
||||
# CMake
|
||||
build*
|
||||
cmake-build-*
|
||||
meson-build-*
|
||||
*.out
|
||||
*.exe
|
||||
|
||||
# Xcode
|
||||
*.xcworkspace
|
||||
*.xcodeproj
|
||||
|
||||
# Visual Studio
|
||||
*.sln
|
||||
*.vcxproj
|
||||
*.vcxproj.filters
|
||||
*.vcxproj.user
|
||||
.vs
|
||||
|
||||
# Makefile
|
||||
Makefile
|
||||
*.make
|
||||
|
||||
# nvim
|
||||
.ccls
|
||||
.ccls-cache
|
||||
compile_commands.json
|
||||
|
||||
# Visual Studio Code
|
||||
.vscode
|
||||
|
||||
# JetBrains
|
||||
.idea
|
||||
.fleet
|
||||
|
||||
# macOS
|
||||
.DS_Store
|
||||
.AppleDouble
|
||||
.LSOverride
|
||||
|
||||
# Cache
|
||||
.cache
|
||||
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