I have a simple code to print the prime factors, but I want to count the numbers for each of the primes and format the output as follows: org_int = p1^e1 * p2 ^ e2…
I’m having issue counting the primes when they occur, where 121 = 11^2
42 = 2^1 * 3^1 * 7^1 is what im going for. I know the count in the current place makes no sense, but im trying to get something down.
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main () {
int integer ;
cout << "enter integer: ";
cin >> integer;
for (int n = 2; n < integer ; n +=1){
while (integer % n == 0) {
count = 0;
integer = integer / n;
count = count + 1;
cout << n^count << endl;
}
}
if (integer != 1) {
cout << integer << endl;
}
}
2
You reinitialize count
inside the loop, so it can only be 1
or 0
Using subfunction, and reworking a little the display might give:
void print_primes_factor(std::size_t n)
{
const char* sep = "";
for (std::size_t i = 2; i < n ; ++i){
std::size_t count = 0;
while (n % i == 0) {
n = n / i;
count = count + 1;
}
if (count != 0) {
std::cout << sep << i;
if (count != 1) {
std::cout << "^" << count;
}
sep = " * ";
}
}
if (n != 1) {
std::cout << sep << n;
}
std::cout << std::endl;
}
Demo