I wrote a program which factorises a number to its prime factors. Therefore what I obviously needed is a function which can do so...
Here is what I want:
1.) Divide the number entered with 2(d). If its divide, print 2 and if n/d is not 1, then print X (multiplication sign) and repeat the function with n/=d.
2.) If the number is not divisible with 2(d), increase d by one and repeat the function (ie with 3)
void factor(int n, int d)// Heart of the program
{
if(n % d == 0)// if n is divisible by d
{
n = n/d;
cout << d;
if(n == 1)
cout << endl;
else
{
cout << " X ";
factor(n,d);
}
}
else
{
d++;
factor(n,d);
}
}
NOTE: I defined int d = 2 up in the main function itself. That's one of the thing I want to get rid of.
What I am asking for is I tried to write this as "for" loop before but I was unsuccessful.
Can anyone suggest that how can I rewrite this function as "for" loop, as I can learn from that.
for (int mytempvariable = 0; mytempvariable < 100; mytempvariable++)
one step at a time:
the first section of the for loop int mytempvariable = 0; makes a new integer variable and stores 0 in it.
the second section of the for loop mytempvariable < 100; is the condition of the for loop. In other words, as long as this statement returns true, run my for loop.
the third section of the for loop mytempvariable++ adds one to the variable every time a loop ends.
This example of a for loop will start at 0, run through the loop with the number being 0, then add 1 to mytempvariable. It will continue on with that pattern until it gets to 99, once it runs through 99, it will add one to the variable, making it 100, which will make the condition (mytempvariable < 100) false. So it will end the loop.
void factor(int n)
{
for(int d = 2; n > 1; /*d++*/)
{
if(n%d == 0)
{
n /= d;
cout << d;
// if (n == 1)
// cout << endl;
// else
// {
if( n > 1 ) //to avoid the trailing " x "
cout << " x ";
// factor(n); //recursion! Why do you need this, you are already in a loop?
// }
} else //only increment d if not a factor
d++;
}
cout << endl; //the loop ends when n == 1
}
Perhaps better written as a while loop:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
void printFactors(int n) {
int d = 2;
while( n > 1 ) {
if( d % n == 0 ) {
//then d is a factor of n
cout << d;
if( n > 1 )
cout << " x ";
n /= d;
} else
d++; //look for the next factor
}
cout << endl; //optional
}