This repository has been archived on 2023-05-13. You can view files and clone it, but cannot push or open issues or pull requests.
mipt_cpp/seminar04_templates/03_factorization/main.cpp

75 lines
1.5 KiB
C++
Raw Normal View History

2022-11-02 22:41:16 +03:00
#include <iostream>
#include <utility>
#include <vector>
#include <cmath>
using std::cout, std::endl, std::pair, std::vector;
int next_prime(int n);
vector<pair<int, int>> factorization(int n) {
if (n == 1) {
return vector<pair<int,int>>{{1, 1}};
}
int d = 2;
int c;
vector<pair<int, int>> result;
while(n != 1) {
c = 0;
while(n % d == 0) {
c++;
n /= d;
}
if (c)
result.push_back(pair{d, c});
d = next_prime(d);
}
return result;
}
bool is_prime(int n) {
bool prime = true;
for(int i = 2; i <= static_cast<int>(std::sqrt(n)); i++) {
if (n % i == 0) {
prime = false;
break;
}
}
return prime;
}
int next_prime(int n) {
++n;
while (true) {
if (is_prime(n))
return n;
++n;
}
}
std::ostream& operator<<(std::ostream& out, pair<int,int> p) {
out << "{" << p.first << ", " << p.second << "}";
return out;
}
std::ostream& operator<<(std::ostream& out, vector<pair<int,int>> v) {
out << "{";
size_t size = v.size();
for(int i = 0; i < size; ++i) {
out << v[i] << (i == size - 1 ? "}" : ", ");
}
return out;
}
int main() {
vector<pair<int, int>> res = factorization(60);
cout << res << endl;
res = factorization(626215995);
cout << res << endl;
res = factorization(107);
cout << res << endl;
res = factorization(1);
cout << res << endl;
}