TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
prime_factorization.cpp
Go to the documentation of this file.
1
5#include <algorithm>
6#include <cstring>
7#include <iostream>
8#include <vector>
9
13bool isprime[1000006];
14
16std::vector<int> prime_numbers;
17
19std::vector<std::pair<int, int>> factors;
20
24 // initializes the array isprime
25 memset(isprime, true, sizeof isprime);
26
27 for (int i = 2; i <= N; i++) {
28 if (isprime[i]) {
29 for (int j = 2 * i; j <= N; j += i) isprime[j] = false;
30 }
31 }
32
33 for (int i = 2; i <= N; i++) {
34 if (isprime[i])
35 prime_numbers.push_back(i);
36 }
37}
38
40void prime_factorization(int num) {
41 int number = num;
42
43 for (int i = 0; prime_numbers[i] <= num; i++) {
44 int count = 0;
45
46 // termination condition
47 if (number == 1) {
48 break;
49 }
50
51 while (number % prime_numbers[i] == 0) {
52 count++;
53 number = number / prime_numbers[i];
54 }
55
56 if (count)
57 factors.push_back(std::make_pair(prime_numbers[i], count));
58 }
59}
60
62int main() {
63 int num;
64 std::cout << "\t\tComputes the prime factorization\n\n";
65 std::cout << "Type in a number: ";
66 std::cin >> num;
67
69
71
72 // Prime factors with their powers in the given number in new line
73 for (auto it : factors) {
74 std::cout << it.first << " " << it.second << std::endl;
75 }
76
77 return 0;
78}
void prime_factorization(int num)
bool isprime[1000006]
std::vector< std::pair< int, int > > factors
int main()
std::vector< int > prime_numbers
void SieveOfEratosthenes(int N)