Guest User

Untitled

a guest
Apr 21st, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.00 KB | None | 0 0
  1. library(gtools)
  2.  
  3. is.prime <- function(num) {
  4. if (num == 2) {
  5. TRUE
  6. } else if (any(num %% 2:(num-1) == 0)) {
  7. FALSE
  8. } else {
  9. TRUE
  10. }
  11. }
  12.  
  13. primesLessThan <- function(limit) {
  14. # Get prime numbers less than or equal to limit.
  15. d <- seq(2:(limit - 1))
  16.  
  17. # Get only those divisors that are prime.
  18. d[sapply(d, is.prime) == TRUE]
  19. }
  20.  
  21. findSums <- function(nums, target) {
  22. # Returns the combinations of nums that sum to the target.
  23. result <- NA
  24.  
  25. for (len in 1:5) {
  26. # Get all permutations of the numbers (repeat numbers allowed).
  27. sets <- permutations(length(nums), len, nums, repeats.allowed=T)
  28.  
  29. # Calculate the sum of each set.
  30. totals <- apply(sets, 1, sum)
  31.  
  32. # Find which set sums to our target.
  33. result <- sets[which(apply(sets, 1, sum) == target),]
  34. if (length(result) > 0) {
  35. break
  36. }
  37. }
  38.  
  39. # Sort and filter the list to distinct numbers.
  40. unique(t(apply(result, 1, sort)))
  41. }
  42.  
  43. goldbach <- function(target) {
  44. findSums(primesLessThan(target), target)
  45. }
Add Comment
Please, Sign In to add comment