Prime Factorization Program

FRESHMAN PROBLEMS!

Gosh I know that this topic may be a piece of cake to you guys but ugh. This is already past due but still, I can't create a coherent code to produce this program.

So if you have time, can you please help me?

Problem:
1. Create a program that computes and prints the prime factors of an integer (long long int).
2. If the input is less than or equal to 1, "incorrect input" should appear.
3. If the input is greater than 1, "the prime factors of n are" should appear. It must also be arranged in ascending order and should be separated by a single space.
4. If a factor is repeated, it should be represented by its exponent/multiplicity form (ex: the prime factors of 36 are 2 2 3 3. The final output should be 2^2 3^2).

Thanks in advance! :):
Last edited on
As others will say, this is not a forum where we will just do your homework. Try to do the problem yourself, and then if you get stuck on certain parts, post your code and ask specifically what the problem is.
Um, I've already done a bit of course; I actually came up with this code (unbelievable) but it only answers nos. 1 to 3.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
using namespace std;
int main()
{
  long long int n;    
  cin >> n;
  if(n <= 1)
    cout << n << " is incorrect input" << endl;
  else
  {
    cout << "The prime factors of " << n << " are ";
    for(int i = 2; i <= n; i++)
    {
      while(n % i == 0)
      {
        n /= i;
        cout << i << " ";
      }
    }
  }
  return 0;
}


Last edited on
Instead of just printing every instance of "i", which would be the prime factor, you would have to keep track of the previous numbers through some sort of memory. The easiest way to do this would probably be by using an array (using std::vector for dynamic run-time size). You see how many 2's through [biggest factor]s are in there, and you cout << factor << "^" << number_times_in_vector;
Last edited on
Topic archived. No new replies allowed.