0

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.

4
Contributors
4
Replies
5
Views
8 Years
Discussion Span
Last Post by Sky Diploma
Featured Replies
  • 1

    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 Read More

  • [code=cplusplus] for(int x=1;x<=(num);x++) [/code] Since 1 is not a prime number don't begin your loop with it, rather initialize x to 2. [B]Definition of prime :[/B] An integer [I][B]greater than one[/B][/I] is called a prime number if its only positive divisors (factors) are one and itself. Read More

  • 2

    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 … Read More

1

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

1
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.

2

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)

Comments
good point on the int capacity
This question has already been answered. Start a new discussion instead.
Take the time to help us to help you. Please be thoughtful and detailed and be sure to adhere to our posting rules.