How to check for prime number

Hi

I am doing this exercise from a book, and I need to be able to identify a prime number. According to the rules, a number is prime number if its odd and the prime number should be divisable with any numbers less or equal to the square root.

I have done the following so far, I hope someone can point out what's wrong here, at times i get 2 statements in the output and sometimes..I get the correct output and sometimes, the program hangs..if I enter the number as 5.

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*q7*/

#include<iostream>
#include<cmath>

using namespace std;

int main()
{
	int positive_integer,number,positive_integer_new,answer;
	double division;
	bool prime;



	cout<<"Enter a positive integer"<<"\n";
	cin>>positive_integer;

	if(positive_integer==2)
	{
		cout<<"This is a prime number"<<"\n";
	}
	else if(positive_integer%2==0)
	{
		cout<<"This is a NOT a prime number, it is divisible by 2 and is even"<<"\n";
	}
	else if(positive_integer%2!=0)
	{
		number=static_cast<int>(pow(positive_integer,0.5));
		positive_integer_new=positive_integer;

		cout<<"The numbers equal and less than the square root is "<<number<<" "<<"\n";
		cout<<"Positive integer "<<positive_integer_new<<" divide "<<number<<" is "<<positive_integer_new/number<<" and the remainder is "<<positive_integer_new%number<<"\n";

		while(positive_integer_new%number!=0)
		{
			
				number=number-2;
				answer=positive_integer_new%number;
				division=positive_integer_new/number;
				if(number!=1)
				{
					cout<<"Positive integer "<<positive_integer_new<<" divide "<<number<<" is "<<division<<" and the remainder is "<<answer<<"\n";

					if(answer!=0)
					{
						prime=true;
					}
					else if(answer==0)
					{
						prime=false;
					}	
				}
			
			
		}
	}

	if(prime=true)
			cout<<"This is a prime number"<<"\n";
	else
		cout<<"This is NOT a prime number"<<"\n";

	return 0;
}
your problem is the while loop. while(positive_integer_new%number!=0) means that it will loop forever if positive_integer_new is prime. lines 38-40 will cause your program to crash if number is even. A simple algorithm to test if a number is prime could look like this:
1
2
3
4
5
6
bool is_prime(int positive_integer){
    for(int number = sqrt(positive_integer); number > 1; number--){
        if(positive_integer % number == 0) return false;
    }
    return true;
}

The idea is to take every number smaller or equal to the root of positive_integer and see if positive_integer can be divided by it. Of course this could be optimized, but I'll leave that to you.
Topic archived. No new replies allowed.