I'm trying to display the prime factors of each number between 1 and 100. I can find the prime factors of individual numbers, but when I try to do the same with each number between 1-100. I believe it's small, but I can't for the life of me find it.
int main()
{
cout << "Enter a number: ";
int num;
cin >> num;
cout<<"The prime factors are: ";
for (int i=2; i <= num; i++)
{
while(num % i == 0)
{
num /= i;// "num" divided by "i" is now "num"
answer+=i;
cout<<i<<" ";
}
}
}
The code above works perfectly and is for finding an individual number's prime factors. The code below is not working and just repeats "2" and should be for each number between 1 and 100.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int main ()
{
for(int test=2;test<100;test++)
{
for(int i=2;i<=test;i++)
{
while (test%i==0)
{
test /= i;
cout<<i<<" ";
}
}
cout<<endl;
}
}
You are using 'test' as a loop counter on line 3.
You are then modifying 'test' on line 9.
What's happening is this:
1) outer for loop starts (line 3). test = 2
2) outer for loop condition is checked (line 3). It's true, so loop keeps going
3) inner for loop starts (line 5). i=2
4) inner for loop condition is checked (line 5). it's true, so the inner loop keeps going.
5) while loop condition is checked (line 7). It's true, so the while loop continues
6) test /= i (line 9). Since test and i are both 2, this means that now... test=1
7) print contents of i (line 10), which prints 2.
8) while loop condition is checked (line 7). It's false so the while loop exits.
9) inner for loop increment occurs (i++ on line 5). Now, i=3 and test=1
10) inner for loop condition checked (line 5). It's false, so the inner loop exits.
11) outer for loop increment occurs (test++ on line 3). Now, test=2
12) << Repeat from #4 >>
As you can see, since you keep dividing test by 2, test never gets any higher, and the endless stream of 2s are printed.
You might want to create two separate variables. One for the loop counter and one for the number whose factors you're searching for.
Line 9 will keep modifying test, interfering with the for loop on line 3 that is trying to simply increment a number by one. You could use a temporary variable there instead.