Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cmath>
- #include <iostream>
- using namespace std;
- unsigned prime_factors(unsigned max, unsigned** factors)
- {
- if (max < 2) {
- return -1;
- }
- // find all prime factors
- bool* is_composite = new bool[max + 1] { false };
- double sup = sqrt(max) + 1;
- for (size_t i = 3; i <= sup; i += 2) {
- if (!is_composite[i]) {
- for (size_t j = 3; i * j <= max; j += 2) {
- is_composite[i * j] = true;
- }
- }
- }
- // calculate the number of prime factors
- unsigned count = 1;
- for (size_t i = 3; i <= max; i += 2) {
- count += !is_composite[i];
- }
- // allocate space and fill in the prime factors
- if (factors != nullptr) {
- *factors = new unsigned[count];
- unsigned index = 0;
- (*factors)[index++] = 2;
- for (size_t i = 3; i <= max; i += 2) {
- if (!is_composite[i]) {
- (*factors)[index++] = i;
- }
- }
- }
- delete[] is_composite;
- return count;
- }
- int main(int argc, char const* argv[])
- {
- unsigned* factors = nullptr;
- unsigned factors_cnt = prime_factors(100, &factors);
- unsigned N;
- cin >> N;
- unsigned exponents[100] = { 0 };
- for (size_t i = 0; i < factors_cnt; i++) {
- while (N % factors[i] == 0) {
- exponents[i]++;
- N /= factors[i];
- }
- }
- for (size_t i = 0; i < factors_cnt; i++) {
- cout << factors[i] << "\t" << exponents[i] << endl;
- }
- cout << N << endl;
- if (factors != nullptr) {
- delete[] factors;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement