简体   繁体   中英

find how many is prime number

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;
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM