'Large integers with boost really slow?
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;
}
Solution 1:[1]
Enabling optimization like -O2 or -O3 will make both calculations (using any: int64 or mp::int128) run faster. Without that, it runs in -O0 which is used mostly for debugging where optimizations cannot be used.
-O3 enables more advanced optimizations, usually at expense of compile time and size. Some suggest that these extra optimizations may not be very safe or well tested.
Also, as @JohnFilleau suggested, you can pass n by reference in isPrime(mp::int128_t n). This is usually faster for non primitive data types. You can also use the const qualifier.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
