Prime number program. Need help!

Hi!
I'm new to programming and I need some help with some of my programs. Bare in mind that I know very little of c++ and may make a lot of mistakes. And english is not my first language either. Anyway, I need some help with this next program. The program has to tell whether a number is prime or not and if not then show every divisor that it has. For example: I enter 12. The output should be something like this: "The divisors of 12 are: 1, 2, 3, 4, 6, 12". And if i had entered 5 then it should have said "prime number".
Here's what I've got so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<iostream>
using namespace std;
int main()
{
    int P;
    cout << "Enter a number: \n";
    cin >> P;
    for (int i = 2; i <= P; i++)
	{
        if (P % i == 0)
		{
         cout << P / i << ",";
               } 
		else
		{
            cout << "Prime number" << endl;
            break;
            }
            }
            system("pause");
            return 0;
            
	}

If a number is prime, it easily says "prime number", but if it is not then it tells some of the divisors and also tells that it's a prime number.
Hope you understood my text.
Thanks for the help!
Your code decides that a number is prime if it finds ANY lower number that doesn't divide evenly. This logic is wrong.
The if-else will run many times in the loop. You need to do the if part in the loop, then set a flag or something, and do that outside of (below) the loop.
Okay, my code is like this:
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
28
29
30
31
32
33
34
35
36
37
#include<iostream>
using namespace std;
int main()
{
    int P, i = 2;
    cout << "Enter a number: \n";
    cin >> P;
    for (i = 2; i <= P; i++)
	{
        if(i == P)
		{
			goto END;
		}
		if (P % i == 0)
		{
		 goto THEEND;
		 }
                
            }
THEEND:
cout << P << " divides with: " << P << ",";
	for (i = 2; i <= P; i++)
	{
		if(P % i == 0)
		{
			cout << P / i << ",";
		}
	}
END:
	if(i == P)
	{
	cout << "Algarv\n";
	}
            system("pause");
            return 0;
            
	}

Everything works fine except when it's not a prime number I want the sentence to end with "." rather than ",". For example:
Input: 6
Output: 6 divides with 6, 3, 2, 1,
what I want:
Output: 6 divides with 6, 3, 2, 1.
Last edited on
Function
http://cplusplus.shinigami.lt/2012/04/05/prime-number-function/
class
http://cplusplus.shinigami.lt/2012/04/05/prime-number-class/
This prints prime numbers, but you can modify to print divisors.
your program to complicated.
Last edited on
all you needed to do for your 1st program was change
for (int i = 2; i <= P; i++)
to
for (int i = 2; i < P; i++)
Topic archived. No new replies allowed.