Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <Rcpp.h>
- #include <iostream>
- #include <vector>
- // This is a simple example of exporting a C++ function to R. You can
- // source this function into an R session using the Rcpp::sourceCpp
- // function (or via the Source button on the editor toolbar). Learn
- // more about Rcpp at:
- //
- // http://www.rcpp.org/
- // http://adv-r.had.co.nz/Rcpp.html
- // http://gallery.rcpp.org/
- //
- // [[Rcpp::export]]
- int divisors_sum(int number) {
- std::vector<int> divisors;
- divisors.push_back(1);
- for (int i = 2; i <= number / 2; i++) {
- if (number % i == 0) {
- divisors.push_back(i);
- }
- }
- int sum = 0;
- for (size_t i = 0; i < divisors.size(); i++)
- sum += divisors[i];
- return sum;
- }
- // [[Rcpp::export]]
- bool is_friendly_c(int x, int y) {
- return (divisors_sum(x) == y) && (divisors_sum(y) == x);
- }
- // You can include R code blocks in C++ files processed with sourceCpp
- // (useful for testing and development). The R code will be automatically
- // run after the compilation.
- //
- /*** R
- divisors_r <- function(x) {
- y <- seq_len(x/2)
- y[ x%%y == 0 ]
- }
- is_friendly_r <- function(x, y) {
- answer <- (x == sum(divisors(y))) && (y == sum(divisors(x)))
- return(answer)
- }
- first = runif(1, 2, 500)
- second = runif(1, 2, 500)
- microbenchmark(
- is_friendly_r(first, second),
- is_friendly_c(first, second)
- )
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement