What's wrong with my program?

This program tests if a number is a prime or not. Although is shows the correct value for 5, 7, etc it doesn't show the correct answer for 2 and 3. Any advice?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  #include <iostream>
using namespace std;
unsigned n;
void prime()
{
    int ok=1;
    if(n<2) ok=1;
    for(int i=2;i<(n/2+1);i++){
        if(n%i==0)
            ok=1;
        else ok=0;
    }
    if(ok==0){cout<<"Prime";}
    if(ok==1){cout<<"Not a prime";}
}
int main()
{
    cin>>n;
    prime();
    return 0;
}
If you tell me

I have an add function that receives two integral parameters and returns their sum, but it is not working! Here is my code:

1
2
3
4
5
int add(int a, int b)
{
    int c = a + a - a + b - b + 4 * b - b - b - b + a;
    return c;
}


I will not tell you

Remove the last addition, + a.

Instead, I will tell you

Just add the numbers inline. But if you insist on using a function, then just do this:

1
2
3
4
int add(int a, int b)
{
    return a + b;
}


Now, back to the problem, why are you using global variables? Why doesn't your function return a Boolean value? Why didn't you call it is_prime or something along those lines?

Peruse this one I just made:

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
bool is_prime(int n)
{
    if (n < 2)
    {
        return false;
    }

    if (n == 2)
    {
        return true;
    }

    if (n % 2 == 0)
    {
        return false;
    }

    for (int i = 3; i * i <= n; i += 2)
    {
        if (n % i == 0)
        {
            return false;
        }
    }
    
    return true;
}


The input is the set of all integers. It returns false for any integer less than two. It returns false for every even integer besides two. It checks only odd integers up to the ceiling of the square root of the given integer (thanks to number theory, we have shown this to be or smallest upper bound).
Last edited on
Thank you so much for explaining!
Another Problem. What parameter should I place in the prime function in order to execute?(main)
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
#include <iostream>
using namespace std;
void prim(int n, int a[100])
{
    int i, j, ok=0;
    cout<<"Prime"<<endl;

    for(i=1;i<=n;i++){
        for(j=2;j<a[i];j++){
            if(a[i]%j==0){
                ok=1; break;
            }
        }
        if(ok==0){cout<<a[i]<<endl;}
    }
}
int main()
{
    int n; int a[100]; int i;
    cin>>n;
    for(i=1;i<=n;i++)
        cin>>a[i];
    prim(n, a[100]);
    return 0;
}
Change this

prim(n, a[100]);

to this

prim(n, a);
Thank You again!
Topic archived. No new replies allowed.