Primes up to 100

Hello!
I should write a function counting how many prime numbers it is up to 7, but I should only call the functoin from main, and function Count could give the right number of them.

Please, how can I avoid in the inner loop that from the
number 6 it adds q+1 when it commes to 3?

Many thanks!!!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  int Count(){
int q=0;
for (int i1=2; i1<=7; i1++){



for (int i2=2; i2<i1; i2++){

if (i1%i2!=0){
q+=1;
break;
}
                            }
                             }

return (q);
                }

int main(){
cout<<Count();
return 0;
You can't use if (i1%i2!=0) to verify whether a number is prime.
However, you can use if (i1%i2==0) to show that the number is not prime.

In the context of your code, you could count how many numbers in the range are not prime, and deduce the number of primes by a simple subtraction. Remember to subtract 1 because the number 1 is not prime.
Last edited on
Hello!
Please ,why is the result here 0 and not 2?


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
 int Count(){
int q=0;
for (int n=2; n<=3; n++){


                         for (int t=2;t<n;t++)        {


                              if (n%t==0){
                                    q+=1;
                                   break;
                                               }


                 else{
                  break;
                         }

                                                                  }                          
                                     
                                                  }

return (q);

                }


int main(){
cout<<Count();
return 0;
}
Last edited on
That version counts how many numbers starting at 2 and ending at 3 are not prime. Zero is the correct answer.

By the way, your code would be much easier to read (for everyone including yourself) if you used a consistent and sensible style of indentation.
http://en.wikipedia.org/wiki/Indent_style

Edit: I think the break; at line 16 is an error. That line should be deleted.
Last edited on
Topic archived. No new replies allowed.