Skip to content

Instantly share code, notes, and snippets.

@Akiyah
Last active October 14, 2015 04:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Akiyah/22b647c0ab045ff34d77 to your computer and use it in GitHub Desktop.
Save Akiyah/22b647c0ab045ff34d77 to your computer and use it in GitHub Desktop.
# http://r-statistics-fan.hatenablog.com/entry/2014/09/22/210455
is.sosu <- function(x){ #素数判定の自作関数作成。(2は判定できない)
sum(x %% 2:sqrt(x) == 0) == 0
}
NUMS <- c(1,3,7,9)
result <- list()
resolve <- function (m, used_nums) {
if (m > 0) {
print(used_nums)
for (num in NUMS) {
resolve(m-1, c(used_nums, num))
}
} else {
k <- 10**rev((1:length(used_nums)) - 1)
x <- sum(k * used_nums)
y <- as.character(sum(k * sort(used_nums)))
if (is.null(result[y][[1]]) || result[y][[1]] == 1) {
#print(paste(x, y, sep=","))
#print(result[y])
#print(is.null(result[y][[1]]))
#result[y] <<- ifelse(is.null(result[y][[1]]), 1, result[y])
if (is.sosu(x)) {
result[y] <<- 1
} else {
result[y] <<- 0
}
}
}
}
system.time(resolve(8, c())) # 4-9まで存在しなかった
df0 <- as.data.frame(unlist(result))
names(df0) <- c('PRIME')
df0$number <- rownames(df0)
df <- df0[df0$PRIME == 1,]
df
# http://r-statistics-fan.hatenablog.com/entry/2014/09/22/210455
is.sosu <- function(x){ #素数判定の自作関数作成。(2は判定できない)
sum(x %% 2:sqrt(x) == 0) == 0
}
# remain_numsをあらゆる並べ方をして、それぞれfをおこない、一つでもTRUEがあれば処理が止まる。
permutation <- function(remain_nums, fixed_nums, f) {
if (sum(remain_nums) == 0) {
rowindex <- names(x[x>0])
result <- f(fixed_nums)
return(result)
}
remain_nums_plus <- remain_nums[remain_nums>0]
for (i in names(remain_nums_plus)) {
y <- remain_nums_plus # clone
y[[i]] <- y[[i]] - 1 # iに対応する部分をマイナス1する
result <- permutation(y, c(fixed_nums, i), f)
if (result) {
return(result)
}
}
return(FALSE)
}
nums_to_integer <- function(nums) {
k <- 10**rev((1:length(nums)) - 1)
i <- sum(k * as.integer(nums)) # 数字文字列の列を数値に変換する
return(i)
}
main <- function(n) { # n >= 2
result <- list()
for (x1 in 0:n) {
for (x3 in 0:(n-x1)) {
#print(c(x1, x3))
for (x7 in 0:(n-x1-x3)) {
x9 <- n-x1-x3-x7
x <- c('1'=x1,'3'=x3,'7'=x7,'9'=x9)
#print(x)
r <- permutation(x, c(), function(nums) {
!is.sosu(nums_to_integer(nums))
})
#print(r)
if (!r) {
result <- c(result, list(x))
#print('hit');
}
}
}
}
return(result)
}
for (n in 2:12) {
print(n)
print(system.time(result <- main(n)))
print(result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment