half of 4th seminar
This commit is contained in:
parent
ca1a5e91b4
commit
52ca816253
8 changed files with 334 additions and 0 deletions
74
seminar04_templates/03_factorization/main.cpp
Normal file
74
seminar04_templates/03_factorization/main.cpp
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
#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;
|
||||
}
|
||||
Reference in a new issue