-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfactor.cpp
More file actions
62 lines (56 loc) · 1.73 KB
/
factor.cpp
File metadata and controls
62 lines (56 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <cstdio>
#include <string>
#include <vector>
#include <cfbox/args.hpp>
#include <cfbox/help.hpp>
#include <cfbox/io.hpp>
#include <cfbox/error.hpp>
namespace {
constexpr cfbox::help::HelpEntry HELP = {
.name = "factor",
.version = CFBOX_VERSION_STRING,
.one_line = "print the prime factors of numbers",
.usage = "factor [NUMBER]...",
.options = "",
.extra = "If no NUMBER is given, read from stdin.",
};
} // namespace
static auto factor_number(unsigned long long n) -> void {
std::printf("%llu:", n);
for (unsigned long long d = 2; d * d <= n; ++d) {
while (n % d == 0) {
std::printf(" %llu", d);
n /= d;
}
}
if (n > 1) std::printf(" %llu", n);
std::putchar('\n');
}
auto factor_main(int argc, char* argv[]) -> int {
auto parsed = cfbox::args::parse(argc, argv, {});
if (parsed.has_long("help")) { cfbox::help::print_help(HELP); return 0; }
if (parsed.has_long("version")) { cfbox::help::print_version(HELP); return 0; }
const auto& pos = parsed.positional();
if (pos.empty()) {
auto input = cfbox::io::read_all_stdin();
if (!input) {
CFBOX_ERR("factor", "%s", input.error().msg.c_str());
return 1;
}
char* str = input->data();
char* end = str + input->size();
while (str < end) {
char* num_end = nullptr;
auto n = std::strtoull(str, &num_end, 10);
if (num_end == str) { ++str; continue; }
factor_number(n);
str = num_end;
}
} else {
for (auto p : pos) {
auto n = std::strtoull(std::string{p}.c_str(), nullptr, 10);
factor_number(n);
}
}
return 0;
}