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:
#include<iostream>
usingnamespace 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!
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.
#include<iostream>
usingnamespace 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.