prime factors of a number

Hello, I had homework to make a C++ program which outputs prime factors of inputed number.

So my program is "supposed to" do something like this:
INPUT: 6
OUTPUT: 3*2*2*1
but guess what, it doesn't. So please can you check what is the error.
Btw, yes I know there is limitation, because I have only 25 prime numbers currently stored in array, but that doesn't matter right now.
Okay, here is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
using namespace std;

void get_prime_factors(int);

int main(){
    int num;
    cout<<"Enter a number: ";
    cin>>num;
    cout<<"\nSolution: "<<endl;
    get_prime_factors(num);
    system("PAUSE");
    return 0;
}

void get_prime_factors(int num){
     int dividers[]={2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97};
     int size=24;
     for(int i=size;i>=2;i--){
             loop:
                  if((num%i==0)&&i>1){
                                    num/=i;
                                    cout<<num/i<<"*";
                                    goto loop;
                                    }
                  else if(i==1){
                       cout<<"*1";
                       break;
                       }
                  else continue;     
                  } 
                                    
                                    }
you don't use the dividers array anywhere. it should be
1
2
3
4
5
6
for(int i = 0; i < 25; i++){//incrementing looks nicer :)
   if(num % dividers[i] == 0){
      num /= dividers[i];
      cout << dividers[i];
   }
}


though this code won't work anyway. for example, 12 = 2*2*3, however your code will only check if the number can be divided by 2 once.
1
2
3
4
5
6
7
8
int i = 2;
while(n > 1){
   while(n % i == 0){
      n /= i;
      cout << i << '*';
   }
   i++;
}
I think should work. It wastes time by checking non prime numbers, but it won't output them.
Topic archived. No new replies allowed.