How to store something in an array instead of displaying it?

I found this code from a post made a while ago:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void Factorize(unsigned u)
{
    for(unsigned i(2);i<=u;i++) //(1)
    {
        if(u%i == 0)
        {   cout << i;
            if (u!=i)
            {
                cout << "*";
                Factorize(u/i);
                return;         //(2)
            }
        }
    }
}


I was wondering how I could store the factors in an array instead of displaying them.
For example:
Now, if you put in "216" as u, it will display: "2*2*2*3*3*3"
Instead, I would want them stored in an array(let's say its called myArray) as:
myArray[0]=2
myArray[1]=2
myArray[2]=2
myArray[3]=3
myArray[4]=3
myArray[5]=3

How can I do that. If possible, modify the code given. If not, please post a new code.
It would be something like this...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int MyArray[10];
int a = 0;

void Factorize(unsigned u)
{
    for(unsigned i(2);i<=u;i++) //(1)
    {
        if(u%i == 0)
        {   MyArray[a] = i;
             a++;
            if (u!=i)
            {
                Factorize(u/i);
                return;         //(2)
            }
        }
    }
}


The only problem is that it will only work once if you plan to use it more than once you need to figure a way to make a=0 when starting
Last edited on
You mean:
vector<int> MyArray[10] ?
Last edited on
should be like that if you use vectors which is better as size in unknown and mush easier to push value to the end,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void Factorize(unsigned u, std::vector<int>& a)
{
    for(unsigned i(2);i<=u;i++) //(1)
    {
        if(u%i == 0)
		{
			a.push_back(i);
            if (u!=i)
			{
                Factorize(u/i, a);
				break;
			}
        }
    }

}


This function takes a vector as a argument and that vector contain the factorzation of the unsigned u.

Usage example:
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
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>

// function implementation goes here

int main()
{
	unsigned h = 216;
	std::vector<int> s;
	Factorize(h,s);// now vector s containe the factorization of 216

  // displaying each element in vector s, seperated by a comma
	std::ostream_iterator<int> o(std::cout,",");
	std::copy(s.begin(),s.end(),o);


	char c[10];

	std::cin.getline(c,10);
}


Last edited on
So would the function implementation be the one you listed above?
Yes! Thank you Damadger, the code works brilliantly.
Yes.
Topic archived. No new replies allowed.