Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- library(gtools)
- is.prime <- function(num) {
- if (num == 2) {
- TRUE
- } else if (any(num %% 2:(num-1) == 0)) {
- FALSE
- } else {
- TRUE
- }
- }
- primesLessThan <- function(limit) {
- # Get prime numbers less than or equal to limit.
- d <- seq(2:(limit - 1))
- # Get only those divisors that are prime.
- d[sapply(d, is.prime) == TRUE]
- }
- findSums <- function(nums, target) {
- # Returns the combinations of nums that sum to the target.
- result <- NA
- for (len in 1:5) {
- # Get all permutations of the numbers (repeat numbers allowed).
- sets <- permutations(length(nums), len, nums, repeats.allowed=T)
- # Calculate the sum of each set.
- totals <- apply(sets, 1, sum)
- # Find which set sums to our target.
- result <- sets[which(apply(sets, 1, sum) == target),]
- if (length(result) > 0) {
- break
- }
- }
- # Sort and filter the list to distinct numbers.
- unique(t(apply(result, 1, sort)))
- }
- goldbach <- function(target) {
- findSums(primesLessThan(target), target)
- }
Add Comment
Please, Sign In to add comment