what is the c++ code for identifying if a number is a prime number or not?


example:
enter number:97
your number is prime
enter number: 4
this is not a prime number!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

int main()
{
	int Number = 0;
	std::cin >> Number;	
	if(Number==1)
	{
		std::cout << "Neither prime not composite" << std::endl;
		return 0;
	}
	for(int i=2; i<=Number/2; i++)
	{
		if(Number%i==0)
		{
			std::cout << "Not Prime" << std::endl;
			return 0;
		}
	}
	std::cout << "Prime" << std::endl;
	return 0;
}
You can find many of these with googling "c++ prime number generator" etc.

Heres one from one of the first results.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <cmath>

bool IsPrime(int num)
{
  // no number can divide into 0
  if(num == 0)
    return true;

  // make sure its not negative
  num = abs(num);

  for(int i = 2; i <= sqrt(num); i++)
    if(num % i == 0)
      return false;
  
  return true;   
}


Haven't bother to look to see if its correct. But it's an easy topic to find. At the least you'll be able to find a heap of different ways to create one.
closed account (z05DSL3A)
It doesn't look good (correct)... Zero...prime! I think not. One...prime, no. Negative numbers! :0)
What ever happened to just answering http://www.cplusplus.com/forum/articles/1295/ to these kinds of questions?
Topic archived. No new replies allowed.