determining prime numbers

Hi,

I'm new with C++ and need help with prime numbers. I need to write a program that determines whether a number is a prime number or not. Here's what my code currently looks like:

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
#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;


int IsPrime(int num)
{
	for(int i = 2; i <= sqrt((double)num); i++)
	{
		int ans;

		if((num % i) == 0 && (i!=1 && i!=num))
			ans = 0;
		else
			ans = 1;
		return ans;
	}
}

int main ()
{
int Number;
char ContinueLoop = 'Y';

while (ContinueLoop == 'Y')
{
		cout <<endl<<endl 
		<<"Please enter a number:  ";
		cin >> Number;
		
		{
		int ans = IsPrime(Number);
			if (ans == 0)
				cout<<"The number is not a prime number";
			else
				cout<<"The number is a prime number";
		}
	
	cout<<"\nDo you want to continue? (Y)  ";
	cin>>ContinueLoop;
	cout<<endl;
	ContinueLoop = toupper(ContinueLoop);
}//end of ContinueLoop
	
	cout<<"\nGood-bye!";

return 0;
}

When I test 15 and 21, my code claims they are prime number (ugh!). Any suggestions for how to determine a prime or if I did something wrong with my code would be appreciated. Thank you
Last edited on
closed account (z05DSL3A)
At the top of this page,do a search for 'Prime' there has been a lot of questions answered about it.
Please use this code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int IsPrime(int num)
{
        int ans=1;

	for(int i = 2; i <= num/2; i++)
	{
		if(num % i == 0)
               {
			ans = 0;
                        break;
               }	
	}

        return ans;
}


PS: This is not the fastest program. For a discussion on the time/space complexity of PRIMES, please see the thread: "Prime number program" by doom at http://www.cplusplus.com/forum/general/1125/
closed account (z05DSL3A)
@msram,
Being pedantic, your code would say that any negative number, zero, and one is prime.
@Grey Wolf: yes... need to check for those basic conditions. Thank you for the comment.

@Turkeycatsmom: Please note Grey Wolf's comment.
Last edited on
msram and Grey Wolf: msram's code worked for me. I appreciate all the help you provided. Thank you again.
Turkeycatmom: In addition to being able to use this code, please understand why your code does not work. That would help you write your code correctly on your own.
Topic archived. No new replies allowed.