prime numbers

I had to write a program that prompts the user to input a positive integer.It should then output a message indicating whether the number is prime number. The problem with my code it is that give the two answer when not it prime. The code is:
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
#include <iostream>
#include <cmath>

using namespace std;

int main ()
{
	int num;
	int i;
	int root;

	cout << "Please enter a number: ";
	cin >> num;
	cout << endl;
	
	root = pow(num, 0.5);

	if (num != 0)
	{
		if (num < 0)
			cout << "Please enter a positive integer."
				 << endl;
		else
			for (i=2; i<= root; i++)
				if (num % i == 0)
					cout << "It is not prime number." << endl;
	}
		
					
cout << "IT A PRIME NUMBER" << endl;


	return 0;
}


I had to use the repetition structure

Thanks!!!
Last edited on
You output that it is a prime number no matter what...

I would add another variable (something like 'bool is_it_prime = true'). Then, when your loop finds that it is _not_ prime, set 'is_it_prime' to false and break the loop.

Then, down at the bottom, use an 'if' statement to check whether is_it_prime is true or false and print an appropriate message.

BTW. You should also be careful about 0 and 1. Neither are prime.

Hope this helps.
I change the code and for number below to 9 they work but if I put 9 or more the program gives me the two output commentes
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
#include <iostream>
#include <cmath>

using namespace std;

int main ()
{
	int num;
	int i;
	int root;
	bool prime;

	cout << "Please enter a positive number: ";
		cin >> num;
		cout << endl;

		root = pow(num, 0.5);

	for (i=2; i<= root; i++)
	 {		
		if (num % i == 0)
		{
			cout << "It is not prime number." << endl;
			prime = false;
		}
		else
		{
		cout << "IT IS PRIME NUMBER." << endl;
		prime = true;
		}
	 }
	

	return 0;
}


Thanks for help me!!
Last edited on
Take a look at your code and think about where the output statements are. Every time through the loop the number is tested against a potential factor and something is printed either way.

You should only declare (print) whether the number is prime or not _after_ checking all possible factors.

Also, you should pay attention to the wording I used in the last post about your 'prime' variable: you should start off assuming it is prime and then disprove it.

Hope this helps.
Last edited on
The pow() function in header <cmath> is defined as double pow(double,double)
That's OK. C++ is capable of doing the appropriate type promotions.
(Your compiler should output a warning to let you know it is doing that though...)
Topic archived. No new replies allowed.