Skip to content

Instantly share code, notes, and snippets.

@stdk
Last active December 29, 2015 11:59
Show Gist options
  • Save stdk/7667234 to your computer and use it in GitHub Desktop.
Save stdk/7667234 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <sstream>
#include <vector>
#include <numeric>
using std::vector;
int main(int argc, char **argv) {
size_t value = 0;
if(argc < 2) {
std::cout << "Usage: factor <number to factorize>" << std::endl;
return 1;
}
std::stringstream in(argv[1]);
in >> value;
if(!in) {
std::cout << "Incorrect input" << std::endl;
return 2;
}
if(!value) {
std::cout << "Oh well." << std::endl;
return 3;
}
std::cout << value << ": ";
const size_t limit = std::min<size_t>(1e8, value/2);
vector<bool> num(limit, true);
vector<size_t> factor;
auto check = [&](size_t candidate) mutable -> bool {
while(value % candidate == 0) {
factor.push_back(candidate);
value /= candidate;
if(value == 1) {
return true;
}
}
return false;
};
if(!check(2)) {
for(size_t i=3; i<limit; i+=2) {
if(num[i]) {
for(size_t k=2*i; k<limit; k+=i) {
num[k] = false;
}
if(check(i)) break;
}
}
}
auto fold = [](size_t a, size_t b) {
std::cout << b << " ";
return a*b;
};
size_t multiplication = std::accumulate(factor.begin(), factor.end(), (size_t)1, fold);
std::cout << "-> " << multiplication << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment