#include <cstdlib>
#include <iostream>
usingnamespace std;
int main()
{
int n;
int i;
cout <<"Enter a Number:";
cin>>n; // lets say n=140
cout<<"Prime Factors:";
for(i=2;i<=n;i++)
{
if(n%i==0)
{
cout << i <<","; // this should show all factors of 140 even if they're not prime
n=n/i; //dont understand this. would n become half if i starts at 2?
i--; //dont understand either would i count down from 140 and does this affect n=n/i?
if(n==1)
break;
}
}
where in this program does it filter prime numbers from the rest and how does it know how many to display?
system("PAUSE");
return (0);
}
n=n/i; //dont understand this. would n become half if i starts at 2?
Yep, but only if n is even
"Your" code is equivalent to
1 2 3 4 5
for( int K=2; K<=n; ++K)
while( n%K == 0 ){ //if the number is a divisor
n /= K; //then divide it
//put K in a divisor container, show it, etc.
}
_ ¿Why it only show prime factors?
_ Because you start with K=2.
In every step you kill every all the 'K' factors from n, so later n%composite would fail.
_ ¿Why i--?
_ Bad style. It's a substitute for the while loop.
You are always doing i++, so in order to kill all the factors, you decrement i and then increment it (do nothing)