简体   繁体   中英

finding a number is prime or not

the code is showing wrong results...it is showing 15,21 and many other odd numbers as prime but they are not...how to fix the problem?..what code should I write in main section[inside int main()]?

#include<bits/stdc++.h>
using namespace std;
#define M 1000000
bool marked[M];



bool sieve(int n)
{
    for (int i = 3; i * i <= n; i += 2)
    {
        if (marked[i] == false)
        {
            for (int j = i * i; j <= n; j += i + i)
            {
                marked[j] = true;
            }
        }
    }
}
bool isPrime(int n)
{
    if (n < 2)
        return false;
    if (n == 2)
        return true;
    if (n % 2 == 0)
        return false;
    return marked[n] == false;
}
int main()
{
    int i,j,k,n,m;
    cin>>n;
    for(i=0; i<n; i++)
    {
        cin>>m;
        if(isPrime(m))
            cout<<"prime"<<endl;
        else
            cout<<"N"<<endl;
    }
}

Is the wrong answer coming due to not properly using or calling functions?.....in this case what should be done.....

My guess is that, since you never call the sieve function, your marked array never gets filled. Since marked is not dynamically allocated, it is zeroed out within your program. Hence, in your isPrime function, all odd numbers will cascade through your if statements and then hit the part where marked[n] == false which would return true since marked[n] is 0 for all of its entries, which is equivalent to the boolean false .

You might want to figure out where it would be best to run the sieve function.

You have wrong increment here:

for (int j = i * i; j <= n; j += i + i)

You need to increase j by i , but you actually increase in by 2*i . Anyway I agree with the previous answer that you never call sieve .

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