$ brew install boost
して、
install.packages('Rcpp')
library(Rcpp)
sourceCpp(code = '
#include <Rcpp.h>
#include <boost/math/common_factor.hpp> // one file, automatically found here
using namespace Rcpp;
// [[Rcpp::export]]
int computeGCD(int a, int b) {
return boost::math::gcd(a, b);
}
// [[Rcpp::export]]
int computeLCM(int a, int b) {
return boost::math::lcm(a, b);
}'
)
で、
> a <- 6
> b <- 15
> cat( c(computeGCD(a,b), computeLCM(a,b)), "\n")
3 30
>
> a <- 96
> b <- 484
> cat( c(computeGCD(a,b), computeLCM(a,b)), "\n")
4 11616
こうなる。
ベンチマーク
> library(rbenchmark)
> library(numbers)
>
> a <- 962
> b <- 4842
>
> benchmark(r1 = c(computeGCD(a,b), computeLCM(a,b)),
+ r2 = c(GCD(a,b), LCM(a,b)),
+ replications = 1000)
test replications elapsed relative user.self sys.self user.child sys.child
1 r1 1000 0.009 1.000 0.008 0.001 0 0
2 r2 1000 0.088 9.778 0.086 0.001 0 0
速い(numbers::GCDとか実装見てないけど)。