Need help!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int num, x;

cout << "Type a number: ";
cin >> num;

x=1;
cout << "The factors of " << num << " are ";
while(x <= num){
	if(num % x == 0){
		cout << x << ", ";
	}
	x++;
}
cout << endl;

cout << "There are " << ______ << " factors";

return 0;
}



How do i count the factors?

example 9 have 3 factors
Last edited on
You can do more than just print a number, if it is a factor. You can increase a counter by one too. The counter must obviously be 0 before the loop starts.


PS. Please, use the code tags in the posts. (You can even edit your older post to add them.)
Try out the Modulo Operator (%)

If the number you want to get the factors from, can be evenly divided (without a rest), its a factor. A number can have multiple factors, as keskiverto already said, thats why you should create a for Loop and increase the number you divide through continuously...

I wouldn't do it with a while Loop...

Something like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int NumberIWantAllTheFactorsFrom;

std::cout << "Enter a number you would like to get all factors from: ";
std::cin >> NumberIWantAllTheFactorsFrom;

int FactorCounter = 0;

for ( int i = 1; i <= NumberIWantAllTheFactorsFrom; i++) 
{
    if ( NumberIWantAllTheFactorsFrom % i == 0 ) //if theres no rest
    {
        std::cout <<  i << ", "; //Creates a list in console Output
        FactorCounter++; // or FactorCounter += 1, whatever you like better
    }
}

std::cout << "There's a total of " << FactorCounter << " Factors for the number " << NumberIWantAllTheFactorsFrom;
Last edited on
@keskiverto
where can i find this code tags?

@HalfNOob
i can only use while loop
May I ask why? O_o


Dont know if this one compiles... I've got no Compiler at work... (+wheres your main function?)
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
26
27

int num = 0;
int x = 1;

std::cout << "Type a number: ";
std::cin >> num;

std::cout << "The factors of " << num << " are ";

int FactorCounter = 0; //Declare the Counter, starting at 0 ofc

while(x <= num)
{
    if(num % x == 0)
    {
        std::cout << x << ", ";
        FactorCounter++; //If theres no rest, add one to the counter
    }
    x++;
}

std::cout << std::endl;

std::cout << "There are " << FactorCounter << " factors";

return 0;
}
Last edited on
its an assignment, rules are I can only use while loop no for or do while.

1
2
3
4
#include <iostream>
using namespace std;

int main(){


it works thanks!



Topic archived. No new replies allowed.