Start New Discussion within our Software Development Community

Hi guys, this is my first week in C++ and was doing some exercises to practice and made a function to calculate primary factors (Still not sure if it works;)
Anyway, here is my code :

#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main()
{
	vector<unsigned long int> vec(0);
	vector<unsigned long int> vec2(0);
	unsigned long int num = 13195;
	unsigned long int num2(1);
	for(unsigned long int i = 1 ; i < num - 1 ; i++)
	{
		if(num % i == 0 && i != 1)
		{
			vec.push_back(i);
		}
	}

	for(unsigned long int i = 0; ; i++)
	{
		
			num *= vec[i];
			vec2.push_back(vec[i]);
		if(num2 == num)
		{
			break;
		}
	}

	for(unsigned long int i = 0 ; i < vec2.size() ; i++)
	{
		cout << vec2[i] << " , ";
	}

	cin.ignore();
	cin.get();
}

I think the error is in the second for loop, the infinite one.. Because before, when I compiled, I had no error, and when I added it, I did. I tried many different combinations for that loop and tried many things and also searched a long time on Google but got no valuable information on this...
Anyway, the error is in the title and I can give more information if demanded :)
Thanks a lot in advance guys;

On line 24 your limiting break statement may be met soon enough so vec becomes longer than vec itself so the error is saying that the subscript ([] is actually called the subscript operator) is too high. Also you dont have to use the break statement, it would be cleaner (though still incorrect logically) to do this:

for(unsigned long int i = 0; num2!=num; i++)
{
num *= vec[i];
vec2.push_back(vec[i]);
}
This article has been dead for over six months. Start a new discussion instead.