I got back into programming as a hobby and I started with one of my favourites: calculating primes. Naturally I wanted bigger numbers. Boost multiprecision seemed good. So I installed it. My program now accepts bigger numbers. So far so good. But it's really slow compared to using a standard int64_t.
To make it less arbitrary: calculating an int64_t 18 digit number which is a prime(100000000000000003) takes about 1sec. With an int128_t roughly 45sec..
I'm partially aware of the issue with it (using different operands for the same thing, probably bad formatting, double declaration of n..)
Here is my code:
#include <iostream>
#include <boost/multiprecision/cpp_int.hpp>
namespace mp = boost::multiprecision;
bool isPrime(mp::int128_t n);
mp::int128_t n{ 0 }, y{ 0 };
int main()
{
std::cin >> y;
std::cin >> n;
std::cout << "\n";
for (y; y <= n; y++)
{
if (isPrime(y) == true)
std::cout << "\033[1;7;32m" << y << "\033[0m ";
else
{
std::cout << y << " ";
}
}
std::cout << "\n";
}
bool isPrime(mp::int128_t n)
{
if (n == 2 || n == 3)
return true;
if (n <= 1 or n % 2 == 0 or n % 3 == 0)
return false;
for (mp::int128_t i = 5; i * i <= n; i += 6)
{
if (n % i == 0 or n % (i + 2) == 0)
return false;
}
return true;
}