-1

I want give array of numberes and find how many of them is prime number,but program give me zero

int Prime_complete(int a[],int len){
    int sum=0;
    int m,flag;
    for(int i=0 ; i<len ; i++){
        m=a[i]/2;  
       for(i = 2; i <= m; i++){ 
            if(a[i] % i == 0){ 
                 flag=1;  
                 break;  
            } 
       
        }  
             if (flag==0)  {
                 sum++;
            }  
     } 
    return sum;
}
Shunya
  • 2,344
  • 4
  • 16
  • 28
  • Suppose the first integer in `a` is composite. `flag` will become set to `1`. When does `flag` go back to `0` if `a[1]` is prime? – Nathan Pierson Jan 06 '22 at 16:35
  • 2
    You didn't initialize `flag` and you don't reset it either. Enable [full warnings](https://stackoverflow.com/questions/57842756/why-should-i-always-enable-compiler-warnings) on your compiler. – jarmod Jan 06 '22 at 16:35

1 Answers1

0

As mentioned already in comments, you need to fix your flag variable to reset each iteration. Right now your code finds a number that isn't prime and then the flag is never reset.

#include <iostream>

using namespace std;

int Prime_complete(int a[],int len)
{
    int sum = 0;
    int flag = 1;
    
    for(int i = 0; i < len; i++)
    {
        for (int j = 2; j < a[i]/2; j++)
        {
            if (a[i] % j == 0)
            {
                flag = 1;
            }
        }
        if (flag == 0)
        {
            sum++;
        }
        flag = 0;
    } 
    return sum;
}

int main()
{
    int numbers[13] = {3, 5, 7, 11, 13, 17, 19, 23, 29, 4, 6, 8, 10};
    cout << Prime_complete(numbers,13);

    return 0;
}

You could also improve your prime checking by only checking values up to the sqrt(a[i]) but that would only be a minor improvement in this case.

MFerguson
  • 1,739
  • 9
  • 17
  • 30