Prime numbers problem

I have no idea why this program of mine doesn't work.
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
#include <iostream>
using namespace std;

int a, nr, n;

int main()
{
    cin>>n;
    for(int i=1; i<=n; i++)
    {
        cin>>a;
        if(a%2!=0 && a%3!=0 && a%5!=0 && a%7!=0)
        {
            nr++;
        }
    }
    if(nr==n)
    {
        cout<<"all the numbers are prime.";
    }
    if(nr!=n)
    {
        cout<<"all the numbers are not prime.";
    }
    return 0;
}

It's supposed to input a set amount of numbers, then tell you if all of them are prime or not.

Also excuse me for my bad english I'm from Sweden.
Hej, har du sett min häst?

Han är grön och liten ;_;
you didn't initialize nr.

Set:
int a, nr=0, n;
I did what you said, but it still doesn`t work... It tells me that all the numbers are not prime even if i input only prime numbers..
Well, your test at line 12 is not the proper way to test for prime numbers.
Let's say you input a = 3.

a%3 is the remainder of 3/3. The remainder is 0. 0!=0 so that will evaluate to false. false && anything is false, therefore you will not enter the if statement and nr will not be incremented.

do something like:
1
2
3
4
5
6
7
8
9
for (int i = 2; i < sqrt(a); ++i)
{
    if (a%i)
    {
        a is not prime;
        break
    }
    a will be prime if not broken in the if in any iteration;
}
For a number to be prime, it can't be divisible by any number less than itself, besides 1. You're only testing divisibility by 2,3,5, and 7.
Topic archived. No new replies allowed.