Advertisement
Guest User

Untitled

a guest
Dec 12th, 2018
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. #include <Rcpp.h>
  2. #include <iostream>
  3. #include <vector>
  4.  
  5. // This is a simple example of exporting a C++ function to R. You can
  6. // source this function into an R session using the Rcpp::sourceCpp
  7. // function (or via the Source button on the editor toolbar). Learn
  8. // more about Rcpp at:
  9. //
  10. // http://www.rcpp.org/
  11. // http://adv-r.had.co.nz/Rcpp.html
  12. // http://gallery.rcpp.org/
  13. //
  14.  
  15. // [[Rcpp::export]]
  16. int divisors_sum(int number) {
  17. std::vector<int> divisors;
  18. divisors.push_back(1);
  19. for (int i = 2; i <= number / 2; i++) {
  20. if (number % i == 0) {
  21. divisors.push_back(i);
  22. }
  23. }
  24. int sum = 0;
  25. for (size_t i = 0; i < divisors.size(); i++)
  26. sum += divisors[i];
  27. return sum;
  28. }
  29.  
  30. // [[Rcpp::export]]
  31. bool is_friendly_c(int x, int y) {
  32. return (divisors_sum(x) == y) && (divisors_sum(y) == x);
  33. }
  34.  
  35. // You can include R code blocks in C++ files processed with sourceCpp
  36. // (useful for testing and development). The R code will be automatically
  37. // run after the compilation.
  38. //
  39.  
  40. /*** R
  41.  
  42. divisors_r <- function(x) {
  43. y <- seq_len(x/2)
  44. y[ x%%y == 0 ]
  45. }
  46.  
  47. is_friendly_r <- function(x, y) {
  48. answer <- (x == sum(divisors(y))) && (y == sum(divisors(x)))
  49. return(answer)
  50. }
  51. first = runif(1, 2, 500)
  52. second = runif(1, 2, 500)
  53.  
  54. microbenchmark(
  55. is_friendly_r(first, second),
  56. is_friendly_c(first, second)
  57. )
  58.  
  59. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement