Reputation: 203
I am trying to find prime numbers between 1,000,000,000,000 and 1,000,000,100,000. My code is OK if the number of digits is 4 to 8, but if the digits are more than or equal to 12 i am getting:
#include <iostream>
#define num 1000000100000
using namespace std;
int main()
{
bool prime;
long double sum = 0;
for (long long int i=1000000000000; i<=num; i++)
{
prime = true;
for(int j=2; j<=i/2; j++)
{
if(i%j == 0) prime = false;
}
if(prime) sum+=i;
}
cout<<sum<<endl;
}
Upvotes: 1
Views: 804
Reputation: 30489
It seems you want to add all prime numbers in range mentioned by you. I would strongly suggest segmented sieve for your purpose.
Or you can do a plain sieving. Take an array of size 100001
to store whether 100000000000 + i
is prime or not. (better if you can do with 100001 / 2
bits) to store only odd number 100000000001 + 2 * i
and sieve out all the odd multiples in range 3 to 1000001
and add the remaining numbers.
But still if you want to stick with your method, I would make a few suggestion to make it run in some practical time.
#include <iostream>
#define num 1000000100000LL // make long long
using namespace std;
int main()
{
bool prime;
long double sum = 0;
for (long long int i=1000000000001LL; i<=num; i += 2LL) // Make long long, loop through only odd numbers as even numbers are not prime except 2
{
prime = true;
for(int j=3; j<=1000001; j += 2) // Loop until sqrt(i) only, loop through odd numbers only
{
if(i%j == 0) {
prime = false;
break;
}
}
if(prime) {
cout << i << endl;
sum+=i;
}
}
cout<<sum<<endl;
}
Upvotes: 1
Reputation: 155
Use unsigned long long int i=1000000000000LL instead of long long int i=1000000000000LL.
Also you have to use the j also as unsigned long long int because the i/2 might not fit in the int j.
Upvotes: 1