Finding Prime Numbers

I have several question.
First time on this site btw as you can probably tell.
Anyways my first question is how do i keep the program keep repeating untill the user presses a certain key like "ctl D" or something to exit.
Also any suggestion to improve the code?

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
  
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
#include <cmath>

void equality (int q){
 if (q==2 || q==3  || q==5 || q==7)
cout << "1 \n";
 }
void test (int w) {
if  ( w>2 && w%2==0 || w>3 && w%3==0
 || w>5 && w%5==0 || w>7 && w%7==0)
{cout<<"0 \n";
 }}




int main (){
 int p;
 cout <<"";
 cin >> p;
 if (p==1){
  cout << "The smallest prime interger is 2 \n";}
 equality (p);
if (p>2){test (p);}

 return 0;
 }
You could check to see if a user types a key say every 1000 numbers or so, or just press Ctrl-C.
unsigned int p
if(p < 2)

for very small primes you can use the built in gcd against the factorial of 7 or if you prefer 2*3*5*7. The values become too large after a while for this trick, though. /shrug is not better, just different. At some point gcd will be more efficient, but for 4 values probably not.



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

using namespace std;

int main() {
	cout << "enter a number: ";
	bool isPrime = true;
	int number;
	cin >> number;

	for (int i = 2; i < (number / 2); i++) {
		if (number % i == 0) {
			cout << "Number is not prime." << endl;
			isPrime = false;
			break;
		}
	}

	if (isPrime == true) {
		cout << "Number is prime." << endl;
	}


	cin.ignore();
	cin.get();

	return 0;
}


This checks if a number is prime.
Its sufficient to check sqrt(number), not number/2.
if you wanted to factor 100, 10*10 is 100, you only need to check 10 values, nothing over 11 will divide into 100 that you haven't already seen (you saw 50 when you looked at 2, you saw 25 when you looked at 4, etc). For even such a small number as 100, that is 40 iterations saved.
Yes, you are right Jonnin. I suppose I was wasting a bit of time looping when it was not needed that much.
Topic archived. No new replies allowed.