最小公倍数がp^m*q^nのときに何通りあるかを計算して表示させるプログラムを書いてみた

# LCM of a,b,c == p^n*q^m -> how many combination and show
pmqn <- function(m=1,n=2,print=TRUE){
(gr=as.matrix(expand.grid(0:m,0:n)))
f0 <- function(x) rep(c('p','q'),x)
(v=c(c('1'),apply(gr[-1,],1,f0)))
f <- function(x){
D=('p' %in% v[x][[1]] & 'p' %in% v[x][[2]] & 'p' %in% v[x][[3]])|('q' %in% v[x][[1]] & 'q' %in% v[x][[3]] & 'q' %in% v[x][[3]])
y=unlist(v[x])
M=sum('p'==y)>=2 & 'q'%in%y
!D&M
}
l=length(v)
ways=sum(combn(l,3,f))
idx=which(combn(l,3,f))
(z=combn(l,3)[,idx])
for(j in 1:ways){
cat(v[z[,j]][[1]], '|',v[z[,j]][[2]],'|',v[z[,j]][[3]],'\n')
}
return(ways)
}