Prime Numbers driving me CRAZY!

Okay, so I have this program here that basically lets you input a number and tells you if it's prime, or not. Every time, I get my critical error message that I built. I was brainstorming the code and got some of it fixed. Help?

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
#include <iostream>
#include <cstdlib>
#include <stdlib.h>
#include <string>
#include <conio.h>

using namespace std;

void error(){
     
     cout << "Error. Repeat # with no decimal and no characters. No 1 allowed";
     }

void critical(){
     
     cout << "\n WARNING critical error!";
     getch();
     void exit(int status);
     }

int main(){
    
    top:
    cout << "Welcome, please enter a number to check for primity: ";
    int enter, result2, boolean;
    double result;
    cin >> enter;
    
    if (enter==1) error();
    
    for (int i=enter-1; i>1; i--){
        result=enter/i;
        result2=result;
        if (result - result2 < 0.0 )boolean=1;
        if (result - result2==0.0) boolean=2;
        else cout << "oops";
        }
    
    if (boolean==1){
       cout << "/n" << enter << " is a prime number!";
       goto top;
       }
    if (boolean==1){
       cout << "/n" << enter << " is NOT prime.";
       goto top;
       }
    else critical();
}


Hope u can help!
floating point numbers are not precise. A floating point number minus an int will almost never be equal to 0, and it gets even less likely that it will be equal to 0.0 . Use modulus (%) to determine if there is no remainder.

Edit: Ditch the gotos
Last edited on
I agree with Intrexa. Forget the double and use a (%).

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

using namespace std;

void error(){
     
     cout << "Error. Repeat # with no decimal and no characters. No 1 allowed";
     }

int main(){
    
while(true){
    cout << "Welcome, please enter a number to check for primity: ";
    int enter;
    bool prime = false;
    cin >> enter;
    
    if (enter<=1) error();
    
    for (int i=1; i<enter/2; i++)
        if (enter%i == 0){
                prime = true;
                break;
        }
    
    if (prime)       cout << "/n" << enter << " is a prime number!";
    else             cout << "/n" << enter << " is NOT prime.";
}
}


As a recommendation, get rid of the "goto" and replace it with a while(true) or something. Goto is bad practice that creates spaghetti code.
Last edited on
Topic archived. No new replies allowed.