Prime number checker 0.1

I have only recently started programming in c++,so I got this idea for prime number checker.

I don't know is it any good but it works(at least i think i works).
My question: is it good ??( for someone who started learning a month ago with antiRTFM).
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
 #include <iostream>

using namespace std;

void mainfunc();


int main(){

	mainfunc();
        return 0;
	 
}


void mainfunc(){
	system("CLS");
	long int test;
	long int ph;
	bool c = true;
	cout << "***********************************************\nEnter your number :";
	cin >> test;
	for (long int i = 2; i < test; i++){
		ph = test % i;
		if (ph == 0){
			cout << test << " is divisble by " << i << endl;
			c = false;
		}

	}//for end
	if (c == true){
		cout << test << " is a prime nuber \n";
	}
	else{
		cout << test << " is not a prime\n";
	}
	cout << "Next number ??(y/n)\n>>>";
	char s = 'y';
	cin >> s;
	if (s == 'y'){
		mainfunc();
	}
	char f;
	cin >> f;
}

Last edited on
You do recursion to repeat the routine. There are cases, where recursion is a good tool, but in your program a do while -loop structure is much more appropriate.


Consider writing an additional function that takes long int and returns bool. Move lines 23-30 into that function. Then you have separated the logic of determining whether a value is prime from the main program that focuses on user interaction. Not necessary, but a good exercise.
It is a very good start.

Checking primes is actually a pretty involved subject.

Your prime checker is deterministic, but slow. Things to consider:
- check 2 before the loop
- in the loop, only check odd numbers
- once you find a factor, you can break out of the loop
- your algorithm currently identifies every factor of the number twice:
  12%3 == 0 should also tell you that 12%4 == 0, since 12/3 == 4
- the question is, then, when can you stop?

Also, concerning line 41, you should prefer a loop to recursion for this kind of thing.

Good job!

[edit] Oh, BTW, that ??( means something. (Do you see
Next number [y/n)
in your prompt?

If you want two exclamation marks next to each other, mark one of them with a backslash:

cout << "Next number \??(y/n)\n>>>";

or

cout << "Next number ?\?(y/n)\n>>>";
Last edited on
Topic archived. No new replies allowed.