I have to find the sum of the prime numbers below 2million so here is the program that i have written.

#include <iostream>

using namespace std;
bool is_prime(int);
int total=0;
int main()
{
    int num=2000000;
    for(int x=1;x<=(num);x++)
    {
        if(is_prime(x)==true)
        {
             total+=x;
             cout<< total<<"\n";
        }
    }
    cout<< total;
    return 0;
}

bool is_prime(int y)
{
    for(int a=1;a<=(y/2);a++)
    {
        if(y%a==0)
        {
            return false;
        }
    }
    return true;
}

I dont know but it gives me 1 as the answer.

Recommended Answers

All 4 Replies

Member Avatar for jencas

If is_prime() is entered with parameter 1 then y/2 evaluates to 0, because a is of type int. So the for loop is not executed and true is returned.
One more tipp: it is sufficient to iterate up to the square root of y instead to y/2

for(int x=1;x<=(num);x++)

Since 1 is not a prime number don't begin your loop with it, rather initialize x to 2.

Definition of prime : An integer greater than one is called a prime number if its only positive divisors (factors) are one and itself.

You start dividing every number by 1! Every integer can be divided by 1 without remainder. Therefore you will always get "false" from your is_prime(int) function.

Secondly, you are going to overflow your int value. There are thousands of prime numbers in between 1 and 2000000. And their sum is way bigger than what int can handle. Use 64bit integer. (long long)

commented: good point on the int capacity +2

Thanks Guys. I know that it was a very silly mistake. But i had to learn someday ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.